如何使用 jQuery 检测键盘上的 Enter 键?

我想用jQuery检测用户是否按下了Enter.

I would like to detect whether the user has pressed Enter using jQuery.

这怎么可能?需要插件吗?

How is this possible? Does it require a plugin?

看来我需要使用 keypress()方法.

It looks like I need to use the keypress() method.

我想知道是否有人知道该命令是否存在浏览器问题 - 比如有没有我应该知道的浏览器兼容性问题?

I wanted to know if anyone knows if there are browser issues with that command - like are there any browser compatibility issues I should know about?

推荐答案

jQuery 的全部意义在于您不必担心浏览器的差异.我很确定您可以安全地使用 enter 在所有浏览器中设置为 13.因此,考虑到这一点,您可以这样做:

The whole point of jQuery is that you don't have to worry about browser differences. I am pretty sure you can safely go with enter being 13 in all browsers. So with that in mind, you can do this:

$(document).on('keypress',function(e) {
    if(e.which == 13) {
        alert('You pressed enter!');
    }
});

相关文章