简体   繁体   English

使用jQuery来监听keydown事件

[英]Using jQuery to listen to keydown event

I want to detect when the enter key is pressed, on HTML that will be injected dynamically. 我想检测何时按下回车键,在动态注入的HTML上。

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. 这段代码适用于on() ,但我担心这是低效的,因为jQuery会在每次按下一个键时检查。 Is there anything inefficient about this? 这有什么低效的吗?

$('body').on('keydown','#textfield', function(event) {
  if (event.keyCode == 13) {
    console.log('Enter was pressed');
  }
}

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. 不要担心这会检查每个按键,这实际上并没有给浏览器带来任何重大负担。

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');
    }
});

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 body and 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的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM