jquery - 检测某个类的输入元素中的输入

标签 jquery class keypress enter

我需要检测何时有人在特定类别的文本输入中点击“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;
    }
});

jsFiddle:http://jsfiddle.net/david_proweb/fjgvhubn/2/

关于jquery - 检测某个类的输入元素中的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13883994/

相关文章:

python - 如何覆盖类,或取消声明类或在 python 中重新声明类?

firebase - Kotlin - 可序列化类中的初始化 block 只能读取默认属性值

javascript - 更改事件不会多次触发同一元素

jquery - XmlHttpRequest 与 jQuery

java - 对对象数组进行排序时出错

c# - 如何使用 C# SendKeys 以编程方式按下 Windows 键

javascript - 当用户在输入上按回车键时如何调用函数

javascript - 如何在 document.getelementById 中尝试 null.value

javascript - 页面刷新后如何保持div隐藏?

Javascript 在平板电脑上读取按键?