Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

javascript - .keyCode与。哪个(.keyCode vs. .which)

I thought this would be answered somewhere on Stack Overflow, but I can't find it.

(我以为可以在Stack Overflow的某处得到答案,但我找不到。)

If I'm listening for a keypress event, should I be using .keyCode or .which to determine if the Enter key was pressed?

(如果我在听一个按键事件,我应该使用.keyCode.which ,以确定是否被按下回车键?)

I've always done something like the following:

(我一直都做以下事情:)

$("#someid").keypress(function(e) {
  if (e.keyCode === 13) {
    e.preventDefault();
    // do something
  }
});

But I'm seeing examples that use .which instead of .keyCode .

(但我看到的例子是使用.which ,而不是.keyCode 。)

What's the difference?

(有什么不同?)

Is one more cross-browser friendly than the other?

(一个跨浏览器比另一个浏览器更友好吗?)

  ask by ScottE translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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年,不赞成使用keyCodewhich而赞成使用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推出基于BlinkV8的替代产品,据推测可以这样做。)


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 )。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...