我需要检测何时有人在特定类别的文本输入中点击“enter”。
我的 jQuery 如下:
$('input.large').keypress(function (e) {
if(e.which ==13)
console.log("pressed enter");
});
我的 HTML 是这样的:
<tr><td> Personal Name </td></tr>
<tr><td> <input type='text' class='large'> </td></tr>
<tr><td> Email</td></tr>
<tr><td> <input type='text' class='large'> </td></tr>
当我给出字段 ID 并尝试 $('#elementid').keypress
时,它起作用了。但这不起作用。我没有得到控制台输出。我错过了什么?
最佳答案
您可以在 document
中使用 keydown
中的实时 ( .on() ) 事件(我认为这更好)。它将允许您检测与选择器匹配的当前和 future 元素中的 keydown
。
HTML:
<strong>Personal Name</strong>
<input type='text' class='large' /><br />
<strong>Email</strong>
<input type='text' class='large' />
JS(jQuery 1.7+):
注意:.which
、.code
、.charCode
和 .keyCode
现在是 deprecated 。使用以下新解决方案:
jQuery(document).on('keydown', 'input.large', function(ev) {
if(ev.key === 'Enter') {
// Will change backgroundColor to blue as example
this.style.backgroundColor = '#EFF';
// Avoid form submit
return false;
}
});
关于jquery - 检测某个类的输入元素中的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13883994/