2017-02-04 89 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(); 
     } 
    }); 

與您點擊做同樣的事情。