使用jQuery的escape key的哪个键代码

本文翻译自: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 characterwhen 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值