jQuery Event Keypress:按下了哪个键?

使用jQuery,如何确定绑定到keypress事件时按下了哪个键?

$('#searchbox input').bind('keypress', function(e) {});

我想在ENTER按下时触发提交

[更新]

即使我找到了(或者更好:一个)自己回答,似乎还有一些变化的空间;)

有没有之间的差异keyCodewhich-尤其是如果我只是在寻找ENTER,这永远不会是一个unicode关键?

有些浏览器提供一种属性,而其他浏览器提供另一种属性吗?

MandyGil2020/03/11 12:32:57

The event.keyCode and event.which are depracated. See @Gibolt answer above or check documentation: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

event.key should be used instead

keypress event is depracated as well: https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event

樱樱2020/03/11 12:32:57

The easiest way that I do is:

$("#element").keydown(function(event) {
    if (event.keyCode == 13) {
        localiza_cep(this.value);
    }
});
小宇宙2020/03/11 12:32:57

Use event.key and modern JS!

No number codes anymore. You can check key directly. For example "Enter", "LeftArrow", "r", or "R".

const input = document.getElementById("searchbox");
input.addEventListener("keypress", function onEvent(event) {
    if (event.key === "Enter") {
        // Submit
    }
    else if (event.key === "Q") {
        // Play quacking duck sound, maybe...
    }
});

Mozilla Docs

Supported Browsers

古一达蒙2020/03/11 12:32:57

Add hidden submit, not type hidden, just plain submit with style="display:none". Here is an example (removed unnecessary attributes from code).

<form>
  <input type="text">
  <input type="submit" style="display:none">
</form>

it will accept enter key natively, no need for JavaScript, works in every browser.

飞云泡芙2020/03/11 12:32:57

Okay, I was blind:

e.which

will contain the ASCII code of the key.

See https://developer.mozilla.org/En/DOM/Event.which

小宇宙LEY2020/03/11 12:32:57

Here is an at-length description of the behaviour of various browsers http://unixpapa.com/js/key.html

Tony神乐2020/03/11 12:32:57

假设您使用的是jQuery,则应绝对使用.which。是的,不同的浏览器设置了不同的属性,但是jQuery将对其进行规范化并分别设置.which值。请参阅http://api.jquery.com/keydown/上的文档,其中指出:

为了确定按下了哪个键,我们可以检查传递给处理函数的事件对象。虽然浏览器使用不同的属性来存储此信息,但jQuery规范化了.which属性,因此我们可以可靠地使用它来检索键码。

米亚伽罗L2020/03/11 12:32:57

实际上这更好:

 var code = e.keyCode || e.which;
 if(code == 13) { //Enter keycode
   //Do something
 }