jQuery:在某些操作中绑定会导致多次执行
好的,我只是要求解除特定按键事件的绑定。我现在用命名空间事件解决了这个问题。但我遇到了另一个问题...下面的函数在 animate()
显示 div 后绑定按键事件。它工作得很好,但按键事件似乎计算了次数,函数被执行...在我的例子中,当单击链接时 myFnc()
执行...所以当我单击链接时keypress.f
事件被触发一次...但是,当在我按下该键之前多次单击该链接时,虽然我只按下该键一次,但 keypress 事件也执行了不止一次time...所以 fadeToggle() 将执行 5 次一次按键,当该功能通过五次点击之前执行了 5 次时……有人明白我的意思并可以帮助我吗?
function myFnc() {
$('#somediv').animate({
height: 'toggle'
}, 600, function() {
$(document).bind('keypress.f', function(event) {
if($('#secret').is(':visible')) {
if ( event.which == 102 ) {
$('.content-2').fadeToggle();
$('.content-284').fadeToggle();
}
}
else {
$(document).unbind('keypress.f');
}
});
});
}
Okay, i just asked for unbinding particular keypress events. I solved this now with namespaced events. But I got another problem...the function below binds a keypress event after a div is shown by animate()
. It works well but the keypress event seems to count the times, the function is executed...in my case the myFnc()
executes when a link is clicked...so when i click the link the keypress.f
event is fired one time...but when the link is clicked more than one time before i press the key, the keypress event also executed more then one time although i pressed the key only one time....so the fadeToggle() will execute 5 times with one keypress, when the function is executed 5 times before through five clicks ...does anyone understand what i mean and can help me with this?
function myFnc() {
$('#somediv').animate({
height: 'toggle'
}, 600, function() {
$(document).bind('keypress.f', function(event) {
if($('#secret').is(':visible')) {
if ( event.which == 102 ) {
$('.content-2').fadeToggle();
$('.content-284').fadeToggle();
}
}
else {
$(document).unbind('keypress.f');
}
});
});
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可以用类似的方法解决这个问题
You could solve this with something like
您正在绑定 5 个 keypress.f 事件(每次单击链接都会绑定一个事件)。您可以通过几种不同的方式解决此问题:
1) 在绑定 keypress.f 事件之前取消绑定所有 keypress.f 事件。
2)页面加载时绑定keypress.f事件,并在函数开头添加if(flag)。每当单击链接时,将标志设置为 true。当您不希望 keypress.f 触发该函数时,将该标志设置为 false。
You are binding 5 keypress.f events (one is bound each time you click the link). You can get around this in a couple different ways:
1) Unbind all keypress.f events before binding the keypress.f event.
2) Bind the keypress.f event when the page loads, and add an if(flag) to the beginning of the function. Whenever the link is clicked, set the flag to true. Set the flag to false when you don't want keypress.f to fire the function.
使用
.is()
方法 和:animated
选择器 仅在当前未进行动画时应用动画..(如果问题是动画播放时多次点击进度)另一种解决方案是在绑定新按键之前始终解除按键绑定。
这样它就永远只是一个。
Use
.is()
method and the:animated
selector to only apply the animation if it is currently not in progress.. (if the issue is multiple clicks while the animation is in progress)another solution would be to always unbind the keypress before binding a new one..
This way it will always be just one..