Using jQuery to listen to keydown event

情到浓时终转凉″ 提交于 2019-12-03 04:06:38

问题


I want to detect when the enter key is pressed, on HTML that will be injected dynamically.

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?

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

回答1:


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.




回答2:


You could still use .on()

$(document).off('keyup#textfield');

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



回答3:


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.



来源:https://stackoverflow.com/questions/14919459/using-jquery-to-listen-to-keydown-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!