Note: The answer below was written in 2010. Here in 2019, both keyCode
and which
are deprecated in favor of key
(for the logical key) and code
(for the physical placement of the key).
(注意:下面的答案写于2010年。这里是在2019年,不赞成使用keyCode
和which
而赞成使用key
(对于逻辑密钥)和code
(对于密钥的物理位置)。)
But note that IE doesn't support code
, and its support for key
is based on an older version of the spec so isn't quite correct.(但请注意,IE不支持code
,并且它对key
支持基于规范的较旧版本,因此不太正确。)
As I write this, the current Edge based on EdgeHTML and Chakra doesn't support code
either, but Microsoft is rolling out its Blink - and V8 - based replacement for Edge, which presumably does/will.(在我撰写本文时,当前基于EdgeHTML和Chakra的Edge也不支持code
,但是Microsoft正在为其Edge推出基于Blink和V8的替代产品,据推测可以这样做。)
Some browsers use keyCode
, others use which
.
(有些浏览器使用的keyCode
,其他人使用which
。)
If you're using jQuery, you can reliably use which
as jQuery standardizes things .
(如果你使用jQuery,您可以可靠地使用which
作为jQuery的标准化的东西 。)
More here.(这里更多。)
If you're not using jQuery, you can do this:
(如果您不使用jQuery,则可以执行以下操作:)
var key = 'which' in e ? e.which : e.keyCode;
Or alternately:
(或替代地:)
var key = e.which || e.keyCode || 0;
...which handles the possibility that e.which
might be 0
(by restoring that 0
at the end, using JavaScript's curiously-powerful ||
operator ).
(...处理e.which
可能为0
的可能性(通过使用JavaScript强大的||
运算符在最后恢复0
)。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…