jQuery:如何使用 live() 捕获按键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1165981/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:48:27  来源:igfitidea点击:

jQuery: how to capture keypress key using live()

jquerylivekeypress

提问by MacAnthony

I need to capture a tab keypress event on some dynamic inputs, but the normal syntax using the keypress event doesn't seem to be catching the key code.

我需要在一些动态输入上捕获 tab keypress 事件,但使用 keypress 事件的正常语法似乎没有捕获关键代码。

$('input').live('keypress', function (e) {
   if ( e.which == 9 )
       alert( 'Tab pressed' );
});

This seems to be catching 0 as the keypress when I go through the debugger in firebug no matter which key I press.

无论我按下哪个键,当我在 firebug 中通过调试器时,这似乎都将 0 作为按键。

回答by Strae

Try it with .keyCode instead of .which:

用 .keyCode 而不是 .which 试试:

$('input').live('keypress', function (e) {
   if ( e.keyCode == 9 ){
       alert( 'Tab pressed' );
    }
});

Seem to work ;)

似乎工作;)

回答by inkedmn

Try listening for keyupor keydowninstead of keypress(per this SO post)

尝试聆听keyupkeydown代替keypress根据此 SO 帖子