问题
Let suppose we have the following JQuery Code:
$(document).bind('keyup', function(e) {
arrows=((e.which)||(e.keyCode));
switch (arrows){
case 37:
executeMyfunction();
break;
}
});
If a user holds down the left arrow key (37) the executeMyfunction() is repeatedly called.
How can I prevent this from happening?
I thought keyup would trigger only if key is released but its not working (thats why i use keyup, keydown does not work either).
回答1:
I believe you have to unbind the event. I think it should not be keyup, but keypress or keydown.
Probably something like this.
$(document).bind('keydown', function(e) {
arrows=((e.which)||(e.keyCode));
switch (arrows){
case 37:
executeMyfunction();
$(document).unbind('keydown');
break;
} });
You will have to rebind the function on keyup if you want to use the event again:
$(document).bind('keyup', function(e) {
switch (arrows){
case 37: $(document).bind('keydown'); break; }
})
Look at: http://api.jquery.com/unbind/
回答2:
Well, you can always debounce the call to your function. That is, if you want your function to be called after the event has not been fired for a short period of time.
来源:https://stackoverflow.com/questions/5254034/javascript-jquery-how-to-prevent-function-from-repeatedly-executed-when-holding