2017-02-04 91 views
0

功能我有点击功能:点击通过Enrr

$("#but").on('click', function(){ 
     $.post('/chat/send/', { 
      id: $(this).attr("name"), text: $('#text').val(), chat_id: $(".message-box").attr("chat-id"), 
       }, function(response) { 
      var options = ''; 
     $.each(response.data, function() { 
     options += '<p><b>' + this[0] + ':</b> ' + this[1] + '</p>'; 
      }); 
     $('#text').val(''); 
     $('.message-box').html(options); 
     }); 
     }); 

当我尝试通过添加回车键也没有什么happend submiting输入的功能。这与输入功能提交:

$('#text').keypress(function(e){ 
     if(e.which == 13){ 
      $("#but").on('click', function(){ 
      $.post('/chat/send/', { 
      id: $(this).attr("name"), text: $('#text').val(), chat_id: $(".message-box").attr("chat-id"), 
       }, function(response) { 
      var options = ''; 
     $.each(response.data, function() { 
     options += '<p><b>' + this[0] + ':</b> ' + this[1] + '</p>'; 
      }); 
     $('#text').val(''); 
     $('.message-box').html(options); 
     }); 
     }); 
     } 
    }); 

在HTML我有:

<input id="text" type="text" name="message-text" size="63"> 
<input id="but" type="submit" name="Send" value="Send"> 
+0

on keypress你不是没有发射你想要的动作,你正在附加事件处理程序到#but元素 – Nic

+0

Thx队友,我是新的jQuery – Hellbea

+0

@Hellbea你可以检查我编辑的答案,它是更优化的。 – PacMan

回答

0

要连接的keypress事件与click里面,所以要解决这个问题;这里是一个建议

尝试factorise重复的代码,所以,如果有任何编辑你所要做的只是一次:

function sendReq(data){ 
     $.post('/chat/send/', data, function(response) { 
       var options = ''; 
      $.each(response.data, function() { 
      options += '<p><b>' + this[0] + ':</b> ' + this[1] + '</p>'; 
       }); 
      $('#text').val(''); 
      $('.message-box').html(options); 
      }); 
    } 

所以你现在具有发送功能您的要求,现在你会处理,你的功能会被解雇的事件,它只是通过键入

$('#text').keypress(function(e){ 
     if(e.keyCode == 13){ 
      var data = {id: $(this).attr("name"), text: $('#text').val(), chat_id: $(".message-box").attr("chat-id")} 
      sendReq(); 
     } 
    }); 

与您点击做同样的事情。