Javascript/JQuery How to prevent function from repeatedly executed when holding down key?

两盒软妹~` 提交于 2019-12-11 07:32:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!