Javascript 使用jQuery监听keydown事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14919459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using jQuery to listen to keydown event
提问by Don P
I want to detect when the enter key is pressed, on HTML that will be injected dynamically.
我想在将动态注入的 HTML 上检测何时按下 Enter 键。
To simply detect when the enter key is pressed, I can do:
要简单地检测何时按下回车键,我可以这样做:
$('#textfield').keydown(function (e){
if(e.keyCode == 13){
console.log('Enter was pressed');
}
})
This code works for on(), but I am worried it is inefficient since jQuery will check every time a key is pressed. Is there anything inefficient about this?
这段代码适用于on(),但我担心它效率低下,因为每次按下一个键时 jQuery 都会检查。这有什么低效的吗?
$('body').on('keydown','#textfield', function(event) {
if (event.keyCode == 13) {
console.log('Enter was pressed');
}
}
回答by Aidan Ewen
If you want to capture the keypress anywhere on the page -
如果您想在页面上的任何位置捕获按键 -
$(document).keypress(function(e) {
if(e.which == 13) {
// enter pressed
}
});
Don't worry about the fact this checks for every keypress, it really isn't putting any significant load on the browser.
不要担心这会检查每个按键的事实,它确实不会给浏览器带来任何重大负载。
回答by MarvinVK
You could still use .on()
你仍然可以使用 .on()
$(document).off('keyup#textfield');
$(document).on('keyup#textfield', function(event) {
if (event.keyCode == 13) {
console.log('Enter was pressed');
}
});
回答by Plynx
In practical terms, nothing you have to worry about. The browser is already going to be bubbling that event, and even though it may be trapped by the bodyand run a selector from the delegated event, this is not a deep or difficult practical check for JQuery to perform, especially with an ID-only selector.
实际上,您无需担心。浏览器已经会冒泡该事件,即使它可能被body委托事件捕获并运行选择器,这对于 JQuery 执行来说并不是一个深入或困难的实际检查,尤其是对于一个只有 ID 的选择器.

