简体   繁体   English

检测按下输入键

[英]Detecting enter key pressed

Are there any ways available in jquery to detect whether Enter key has pressed? jQuery中是否有任何方法可以检测是否已按下Enter键?

I know that we can use keycodes/charset to identify the Enter key press, but I do not need to hard code an integer value in my js script as it will become a magical number. 我知道我们可以使用键码/字符集来标识Enter键,但是我不需要在我的js脚本中对一个整数值进行硬编码,因为它会变成一个神奇的数字。 I need to know whether there are any other possible ways to detect Enter key press, which is something like e.shiftKey for detecting shift key press using event object. 我需要知道是否还有其他可能的方法来检测Enter键的按下,这类似于e.shiftKey用于使用事件对象来检测Shift键的按下。

Thanks. 谢谢。

So, you want to detect the Enter key being pressed without hardcoding a 13 for the keycode. 因此,您想检测是否按下了Enter键,而没有将键码硬编码为13

Now, I could suggest using 6.5*2 as the keycode, then, but that'd be silly. 现在,我可以建议使用6.5*2作为键码,但这很愚蠢。

The real answer is that there is no built-in constant for the Enter key, like the Shift key has. 真正的答案是,像Shift键一样, Enter键没有内置常数。

The reason Shift has it, is because that key is often pressed in combination with other keys. Shift之所以具有此功能,是因为该键经常与其他键一起按下。 You can't detect a Shift keyDown event when pressing Shift + A , for example, because the event for the modifier has passed already when you're handling the keyDown event for the A . 例如,在按Shift + A时 ,您无法检测到Shift keyDown事件,因为在处理AkeyDown事件时,修饰符的事件已经通过。

Frankly, your only real option would be to hardcode a application-wide constant that says something along the lines of: 坦白说,您唯一真正的选择是对应用程序范围内的常量进行硬编码,该常量类似于以下内容:

window.keyCodes = {
    Enter: 13,
    SomeKey: 99
}

Then you can check against it like this: 然后您可以像这样检查它:

if(e.keyCode === keyCodes.Enter)

Or, it may be possible to write a function that compares the character of the entered key with a string that contains only a return, but then you'd just be hardcoding a return, any way. 或者,可以编写一个函数,将输入的键的字符与仅包含返回值的字符串进行比较,但是您将只能以任何方式对返回值进行硬编码。

The keycode for the enter key is : 13 回车键的键码是:13

if(e.keyCode == 13)
  //do something...

This is the immediate way that people detect this particular event, but there are other ways to identify the number 13. 这是人们检测到此特定事件的直接方法,但是还有其他方法可以识别数字13。

var DOM_VK_RETURN = 13;

$(document).on('keydown', function(e) {
  var code = e.keyCode || e.which;
  if(code == DOM_VK_RETURN) {
    console.log("Enter key pressed");
  }
});

However, if you do not want to use an integer to detect the key, we could use hexadecimal. 但是,如果您不想使用整数来检测密钥,则可以使用十六进制。

http://jsfiddle.net/hk2eL/3/ http://jsfiddle.net/hk2eL/3/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM