.keyCode vs. .which [英] .keyCode vs. .which
问题描述
我以为这会在Stack Overflow的某个地方得到解答,但我找不到它。
I thought this would be answered somewhere on Stack Overflow, but I can’t find it.
如果我正在听一个按键事件,我应该是使用 .keyCode
或 .which
确定是否按下了Enter键?
If I’m listening for a keypress event, should I be using .keyCode
or .which
to determine if the Enter key was pressed?
我总是这样做:
$("#someid").keypress(function(e) {
if (e.keyCode === 13) {
e.preventDefault();
// do something
}
});
但我看到的例子使用 .which
而不是 .keyCode
。有什么不同?一个浏览器是否比另一个更友好?
But I’m seeing examples that use .which
instead of .keyCode
. What’s the difference? Is one more cross-browser friendly than the other?
推荐答案
某些浏览器使用 keyCode
,其他人使用
。如果你正在使用jQuery,你可以可靠地使用哪个
作为jQuery 标准化事物。 此处了解更多信息。
Some browsers use keyCode
, others use which
. If you're using jQuery, you can reliably use which
as jQuery standardizes things. More here.
如果你没有使用jQuery,你可以这样做:
If you're not using jQuery, you can do this:
var key = 'which' in e ? e.which : e.keyCode;
或者可选择:
var key = e.which || e.keyCode || 0;
...处理 e.which $ c的可能性$ c>可能是
/blog.niftysnippets.org/2008/02/javascripts-curiously-powerful-or.htmlrel =noreferrer> JavaScript奇特强大的 0
(最后通过使用 0 ||
运算符)。
...which handles the possibility that e.which
might be 0
(by restoring that 0
at the end, using JavaScript's curiously-powerful ||
operator).
这篇关于.keyCode vs. .which的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!