如何找出用户在文本输入中按“输入”

How to find out user pressed "enter" in text input?

本文关键字:输入 文本 何找出 用户      更新时间:2023-09-26

当用户按回车键时,我正在尝试将文本输入的元素添加到我的数组中。 但我不知道该怎么做。我试过这个if语句,但它们不起作用:

var val = $("#txbxfeeds").val();
if (val[val.length-1] == "'r") {
    alert("HI");
}
if (val[val.length-1] == "'n") {
    alert("HI");
}

我该怎么做?

我可以提出以下建议:

var vals = [];
$("#txbxfeeds").on("keypress", function(e) {
    if (e.which == 13) {
        vals.push(this.value);
    }
});

演示:http://jsfiddle.net/Q4CUf/

$("#txbxfeeds").on('keyup', function(e) {
   //13 is the code for enter button
   var val = $(this).val(); // or this.value
   if(e.which == 13) {
    alert( val );
   }
});

工作样品

阅读更多关于 jQuery event.which