2017-03-09 118 views
0

我想使按jQuery發送數據,但我的代碼不工作。任何人都可以告訴我我在這裏錯過了什麼?Jquery keydown不會工作

<textarea name="reply" class="reply" id="replyChat" placeholder="Write your message"></textarea> 

JS

function SendMessage() { 
     $.ajax({ 
     type: "POST", 
     url: "/ajax/reply", 
     data: dataString, 
     cache: false, 
     success: function(html) { 
      $('.messages-body').append(html); 
     } 
     }); 
    } 

    $('#replyChat').bind('keydown', function(e) { 
     if(e.keyCode==13) { 
     SendMessage(); 
    } 
    }); 
    $('body').on("click",".reply-btn",function() { 
    SendMessage(); 
}); 

點擊功能工作正常,只是KEYDOWN不在這裏工作了。

+1

它的工作對我來說,是件動態生成 –

+0

您可以發佈的jsfiddle – ArUn

+0

是您的文檔準備函數內部的代碼? – osanger

回答

1

使用event delegation作爲動態生成的元素,儘管使用了jQuery建議的event.which屬性。

function SendMessage() { 
 
    console.log('hi'); 
 
    // replace with your ajax code 
 
} 
 

 
$('body').on('keydown', '#replyChat', function(e) { 
 
    if (e.which == 13) { 
 
    SendMessage(); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<textarea name="reply" class="reply" id="replyChat" placeholder="Write your message"></textarea>