Javascript/JQuery如何防止在按住键时重复执行功能? [英] Javascript/JQuery How to prevent function from repeatedly executed when holding down key?
问题描述
假设我们有以下JQuery代码:
Let suppose we have the following JQuery Code:
$(document).bind('keyup', function(e) {
arrows=((e.which)||(e.keyCode));
switch (arrows){
case 37:
executeMyfunction();
break;
}
});
如果用户按住左箭头键(37),则会重复调用executeMyfunction().
If a user holds down the left arrow key (37) the executeMyfunction() is repeatedly called.
如何防止这种情况发生?
How can I prevent this from happening?
我认为只有在释放键但它不起作用的情况下,keyup才会触发(这就是为什么我使用keyup,keydown也不起作用).
I thought keyup would trigger only if key is released but its not working (thats why i use keyup, keydown does not work either).
推荐答案
我相信您必须取消绑定该事件.我认为它不应该是按键,而是按键或按键.
I believe you have to unbind the event. I think it should not be keyup, but keypress or keydown.
大概是这样的.
$(document).bind('keydown',function(e){
$(document).bind('keydown', function(e) {
arrows =(((e.which)|||(e.keyCode));
arrows=((e.which)||(e.keyCode));
开关(箭头){
案例37:
executeMyfunction();
executeMyfunction();
$(document).unbind('keydown');
$(document).unbind('keydown');
休息;
} });
如果要再次使用该事件,则必须在keyup上重新绑定该功能:
You will have to rebind the function on keyup if you want to use the event again:
$(document).bind('keyup',function(e){
$(document).bind('keyup', function(e) {
开关(箭头){
案例37: $(document).bind('keydown'); 休息; }
case 37: $(document).bind('keydown'); break; }
})
查看: http://api.jquery.com/unbind/
这篇关于Javascript/JQuery如何防止在按住键时重复执行功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!