jQuery's 'keypress' doesn't work f

2019-01-21 21:16发布

I'm trying to implement key-press functionality which will remove a div when the user hits Esc. This works for Firefox & IE with the following code:

$("body").keypress(function(e) {
    alert("any key pressed");
    if (e.keyCode == 27) {
        alert("escape pressed");
    }
});

If I hit any key, the first alert is displayed, and if I hit Escape, the second alert is also displayed.

This doesn't work with Chrome though. The first alert is always displayed if I hit any of the letter keys, but not when I hit Escape, Tab, Space or any of the numbers.

Why would this be? Is there any way to get Chrome to respond to these key presses?

6条回答
【Aperson】
2楼-- · 2019-01-21 21:47

keypress 'ESC'

e.which: 0
e.keyCode: 27

keyup 'ESC'

e.which: 27
e.keyCode: 27

For non-printable characters better use keyup.

查看更多
够拽才男人
3楼-- · 2019-01-21 21:49

After the second alert add also

e.preventDefault();

This will prevent the default action of the event to be triggered.

More info about this method here

Your code should look like

$("body").keypress(function(e) {
    alert("any key pressed");
    if (e.keyCode == 27) {
         alert("escape pressed");
         e.preventDefault();
}});
查看更多
一纸荒年 Trace。
4楼-- · 2019-01-21 21:55

Using Jquery.hotkey js file you can Make Sortcut key

$(document).bind('keydown', 'esc', function(){ });
查看更多
叼着烟拽天下
5楼-- · 2019-01-21 21:59

Try handling keydown instead.

查看更多
相关推荐>>
6楼-- · 2019-01-21 22:08

use keydown. keypress doesn't work with ESC in Chrome (not sure about other browsers).

$(newTag).keydown(function(e) {  //keypress did not work with ESC;
    if (event.which == '13') {
      ProfilePage.saveNewTag(search_id, $(newTag).val());
    }
    else if (window.event.which){
      $(newTag).remove();
    }
}); 
查看更多
淡お忘
7楼-- · 2019-01-21 22:11

For ESC key:

$(document).keydown(function(e) {
  if(e.keyCode == 27) { /* Run code */ }
}

For letter keys, like 'L':

$(document).keypress(function(e) {
  if(e.which == 108) { }
});

Works in both Chrome and Firefox

查看更多
登录 后发表回答