试图找出 jQuery 中是否存在错误或者这是否是我正在做的事情
$(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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
which
属性是按下哪个键的“一站式服务”,允许您忽略keyCode
和charCode
属性之间的差异。这就是 jQuery 提供的“规范化”。which
值的差异归结为不同浏览器提供信息的方式之间的差异 - 因此您必须编写代码来处理返回的不同值。网上有关于此行为的一些参考资料。The
which
property is a "one stop shop" for which key was pressed, allowing you to ignore the differences between thekeyCode
andcharCode
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.快速 Google 搜索 表明您只需对两者进行测试即可。这是与 Firefox 一贯的不一致之处。
A quick Google search says you will simply have to test for both. This is a consistent inconsistency with Firefox.
我不了解 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.
以下是 jQuery 所做的全部“规范化”:
看起来如果
charCode
不存在,它只会获取keyCode
。仅当event.which
尚不存在时才使用charCode
。它不会改变周围的数字以使它们保持一致。Here is the entirety of the "normalization" that jQuery does:
Looks like it just gets
keyCode
ifcharCode
doesn't exist. AndcharCode
is only used ifevent.which
doesn't already exist. It doesn't change the numbers around to make them consistent.