jQuery doesn't detect "left" keypress inside input box
My code is
$('input').live('keypress', function(event) {
if (event.keyCode === 37) console.log("left key pressed");
else console.log("some other key press");
});
Plea开发者_如何学JAVAse see http://jsfiddle.net/4RKeV/
This detects keypresses, but not the left keypress (keyCode 37). How can I detect left keypress?
In short: don't use the keypress
event. Use keydown
or keyup
instead.
The keypress
event is not covered by any official specification. As such, keypress
does not have well-defined behavior, will not work the same way across browsers, and will act capriciously and unpredictably. (Read more [quirksmode.org])
As an alternative to keypress
, you should use one of these events:
keydown
[w3c spec] -- This triggers when a key is pressed down and continues to trigger while the key is held down.keyup
[w3c spec] -- This triggers when the key is lifted up.
I would probably fix it by using keydown
because it is probably closer to what you were expecting keypress
to do:
$('input').live('keydown', function(e) {
if (e.which === 37) { console.log("left key pressed"); }
else { console.log("some other key press"); }
});
P.S. I changed e.keyCode
to e.which
, because it is more cross-browser compliant.
Change your binding event to keyup
:
$('input').live('keyup', function(event) {
if (event.keyCode === 37) console.log("left key pressed");
else console.log("some other key press");
});
精彩评论