jquery - 使用 JQuery 绑定(bind)按键事件在 Chrome 中不起作用

标签 jquery ubuntu google-chrome

我正在使用 Ubuntu 10 并在 Firefox 3.6 和 Chrome 5 中尝试以下代码。

    $(document).ready(function(){
        $(document).bind("keypress", function(e){
            alert("Pressed");
        });
    });

令人惊讶的是,上面的代码在 FF3.6 中运行良好。即每按下一个键,我都会收到一个警报框。

但在 Chrome 中,我看到了不同的行为。例如,当我按上/下翻页、上/下/左/右箭头键时,我没有收到警报框(不幸的是,这些是我迫切想要跟踪的关键事件)。

有人知道为什么 Chrome 没有将“按键”事件绑定(bind)到某些按键,例如向上/向下翻页、向左/向右箭头吗?

最佳答案

onkeypress 事件最初是 Internet Explorer 的专有事件,后来包含在其他浏览器中,但实现不同。 Chrome/Safari 忠实于 Microsoft 实现,为此 the documentation状态:

As of Microsoft Internet Explorer 4.0, the onkeypress event fires and can be canceled for the following keys:

Letters: A - Z (uppercase and lowercase)
Numerals: 0 - 9
Symbols: ! @ # $ % ^ & * ( ) _ - + = < [ ] { } , . / ? \ | ' ` " ~
System: ESC, SPACEBAR, ENTER

对于其他按键,您应该绑定(bind)到 keydownkeyup

Quirksmode.org compatibility reference状态:

When the user presses special keys such as the arrow keys, the browser should NOT fire keypress events.

关于jquery - 使用 JQuery 绑定(bind)按键事件在 Chrome 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3417938/

相关文章:

javascript - JavaScript 中的高效方法

java - 我找不到 java17 以外版本的 javac

ruby-on-rails - Cap Deploy 在新客户端机器上失败

javascript - 从 JavaScript 添加到浏览器收藏夹/书签但适用于所有浏览器(我的浏览器在 Chrome 中不起作用)?

jquery - 如何使用 jQuery 在多个 ID 上设置属性?

jquery - 谷歌地图嵌入与粘性导航栏重叠

javascript - jQuery iBox(灯箱克隆)和 IFRAMES

windows - 如何在 Windows 上重置 Ubuntu 的管理员密码

google-chrome - 谷歌浏览器缓存问题

c - 在 C/Go 中从 Google Chrome 获取标签页信息