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. 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)
});

尝试使用关键事件:

$(document).keyup(function(e) {
  if (e.keyCode === 13) $('.save').click();     // enter
  if (e.keyCode === 27) $('.cancel').click();   // esc
});

Rather than hardcode the keycode values in your function, consider using named constants to better convey your meaning:

var KEYCODE_ENTER = 13;
var KEYCODE_ESC = 27;

$(document).keyup(function(e) {
  if (e.keyCode == KEYCODE_ENTER) $('.save').click();
  if (e.keyCode == KEYCODE_ESC) $('.cancel').click();
});

Some browsers (like FireFox, unsure of others) define a global KeyEvent object that exposes these types of constants for you. This SO question shows a nice way of defining that object in other browsers as well.


(Answer extracted from my previous comment)

You need to use keyup rather than keypress . eg:

$(document).keyup(function(e) {
  if (e.which == 13) $('.save').click();     // enter
  if (e.which == 27) $('.cancel').click();   // esc
});

keypress doesn't seem to be handled consistently between browsers (try out the demo at http://api.jquery.com/keypress in IE vs Chrome vs Firefox. Sometimes keypress doesn't register, and the values for both 'which' and 'keyCode' vary) whereas keyup is consistent.

Since there was some discussion of e.which vs e.keyCode : Note that e.which is the jquery-normalized value and is the one recommended for use:

The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.

(from http://api.jquery.com/event.which/)

链接地址: http://www.djcxy.com/p/94924.html

上一篇: 函数之前的加号是什么?

下一篇: jQuery使用哪个键码进行换码