本文翻译自:Which keycode for escape key with jQuery
I have two functions. 我有两个功能。 When enter is pressed the functions runs correctly but when escape is pressed it doesn't. 当按下enter时,功能正常运行,但是当按下escape时它不会。 What's the correct number for the escape key? 转义键的正确数字是多少?
$(document).keypress(function(e) {
if (e.which == 13) $('.save').click(); // enter (works as expected)
if (e.which == 27) $('.cancel').click(); // esc (does not work)
});
#1楼
参考:https://stackoom.com/question/4rlo/使用jQuery的escape-key的哪个键代码
#2楼
27 is the code for the escape key. 27是转义键的代码。 :) :)
#3楼
Try with the keyup event : 尝试使用keyup事件 :
$(document).keyup(function(e) {
if (e.keyCode === 13) $('.save').click(); // enter
if (e.keyCode === 27) $('.cancel').click(); // esc
});
#4楼
要获取所有字符的十六进制代码: http : //asciitable.com/
#5楼
To find the keycode for any key, use this simple function: 要查找任何键的键码,请使用以下简单功能:
document.onkeydown = function(evt) {
console.log(evt.keyCode);
}
#6楼
To explain where other answers haven't; 解释其他答案没有的地方; the problem is your use of keypress . 问题是你使用keypress 。
Perhaps the event is just mis-named but keypress is defined to fire when when an actual character is being inserted . 也许事件只是错误命名,但是when an actual is being inserted when an actual character时when an actual keypress被定义为触发。 Ie text. 即文字。
Whereas what you want is keydown / keyup , which fires whenever (before or after, respectively) the user depresses a key . 而你想要的是keydown / keyup ,它会在the user depresses a key时(分别在之前或之后)触发。 Ie those things on the keyboard. 就是键盘上的那些东西。
The difference appears here because esc is a control character (literally 'non-printing character') and so doesn't write any text, thus not even firing keypress . 这里出现的差异是因为esc是一个控制字符 (字面意思是“非打印字符”)因此不会写任何文本,因此甚至不会触发keypress 。 enter is weird, because even though you are using it as a control character (ie to control the UI), it is still inserting a new-line character, which will fire keypress . enter很奇怪,因为即使你将它用作控制字符(即控制UI),它仍然会插入一个新行字符,它将触发keypress 。
Source: quirksmode 资料来源: quirksmode

1508

被折叠的 条评论
为什么被折叠?



