Possible Duplicate:
JavaScript event.keyCode constants
This is my code:
$button.on('keyup', function (event) {
// Detect an Enter keypress
if(event.keyCode === 13) {
doStuff();
}
});
As you can see, the keycode 13
is hardcoded. Is there a (cross-browser) way to fish out that number in a more semantically meaningful way?
If you work with jQueryUI, you may use $.ui.keyCode
constants:
keyCode: {
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
}
So in order to check for Enter pressed use:
if (event.keyCode === $.ui.keyCode.ENTER) { ... }
To repeat Alex K.
's answer (I used):
"\r".charCodeAt(0)
来源:https://stackoverflow.com/questions/14276957/javascript-avoiding-hardcoded-keycodes