试图找出 jQuery 中是否存在错误或者这是否是我正在做的事情

发布于 2024-12-11 15:06:57 字数 308 浏览 0 评论 0原文

$(document).keydown(function (event)
    {
    alert(event.which);
    });

对于分号键 ;,这在 Firefox 中给出 59,在 Chrome 中给出 186。然而,从 keydown 事件的 jQuery 参考页面来看,它说

“虽然浏览器使用不同的属性来存储此信息,但 jQuery 规范了 .which 属性,以便您可以可靠地使用它来检索关键代码。此代码对应于键盘,包括特殊键(例如箭头)的代码。”

我错过了什么吗?

$(document).keydown(function (event)
    {
    alert(event.which);
    });

For the semicolon key, ;, this gives 59 in Firefox and 186 in Chrome. However, from the jQuery reference page for the keydown event, it says

"While browsers use differing properties to store this information, jQuery normalizes the .which property so you can reliably use it to retrieve the key code. This code corresponds to a key on the keyboard, including codes for special keys such as arrows."

Am I missing something?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

草莓味的萝莉 2024-12-18 15:06:58

which 属性是按下哪个键的“一站式服务”,允许您忽略 keyCodecharCode 属性之间的差异。这就是 jQuery 提供的“规范化”。

which 值的差异归结为不同浏览器提供信息的方式之间的差异 - 因此您必须编写代码来处理返回的不同值。网上有关于此行为的一些参考资料

The which property is a "one stop shop" for which key was pressed, allowing you to ignore the differences between the keyCode and charCode properties. That is the "normalization" that jQuery provides.

The difference in the value of which comes down to a difference between the way the various browsers supply the information - so you'll have to write code to handle the different values that come back. There are a few references to this behavior online.

相权↑美人 2024-12-18 15:06:58

快速 Google 搜索 表明您只需对两者进行测试即可。这是与 Firefox 一贯的不一致之处。

A quick Google search says you will simply have to test for both. This is a consistent inconsistency with Firefox.

熊抱啵儿 2024-12-18 15:06:58

我不了解 jQuery,但我建议坚持使用 keypress 事件来键入按键,并且仅对特殊键(例如箭头)使用 keydown 事件。

I don't know about jQuery but I'd suggest sticking to keypress events for typing keys and only using keydown events for special keys such as arrows.

新雨望断虹 2024-12-18 15:06:58

以下是 jQuery 所做的全部“规范化”:

if ( event.which == null ) {
    event.which = original.charCode != null ? original.charCode : original.keyCode;
}

看起来如果 charCode 不存在,它只会获取 keyCode。仅当 event.which 尚不存在时才使用 charCode。它不会改变周围的数字以使它们保持一致。

Here is the entirety of the "normalization" that jQuery does:

if ( event.which == null ) {
    event.which = original.charCode != null ? original.charCode : original.keyCode;
}

Looks like it just gets keyCode if charCode doesn't exist. And charCode is only used if event.which doesn't already exist. It doesn't change the numbers around to make them consistent.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文