在下面的代码片段中,只有当我连续停留在 div
一段时间后,我才想调用 change()
函数。如果我只是浏览 div
,我想取消对该函数的调用 - 使用 clearTimeout
。
我看到 clearTimeout 不工作。有人请帮助我。提前致谢。
jQuery 部分:
var obj=$('#aaa');
var tt;
obj.find('div').bind({
mouseenter:function(e){
var that = $(this)
tt = setTimeout(function(){
change(e,that)
},1000) // <-- time to wait before execution
},
mouseleave:function(e){
clearTimeout(tt);
}
});
function change(e,that){
console.log(e)
console.log(that)
}
HTML 部分:
<div id='aaa'>
<div><!--class a start-->
<div>lkaiseulaweg</div>
<div><!--class b start-->
<div>ae</div>
<div>dd</div>
</div><!--class b end-->
</div><!--class a end-->
<div><!--class a start-->
<i>numbers</i>
<div><!--class b start-->
<div>986</div>
<div>345</div>
<div>000</div>
<div>999</div>
</div><!--class b end-->
</div><!--class a end-->
</div>
最佳答案
每个 div 都需要一个额外的闭包,以便 tt
变量是唯一的。使用 .each
绑定(bind)事件监听器,有效地为每个 tt
变量创建一个新的闭包:
obj.find('div').each(function(){
var tt;
var that = $(this)
that.bind({
mouseenter:function(e){
clearTimeout(tt); // In case something weird happens
tt = setTimeout(function(){
change(e,that)
},1000) // <-- time to wait before execution
},
mouseleave:function(e){
clearTimeout(tt);
}
});
});
关于javascript - jQuery-Javascript setTimeout-clearTimeout 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7979840/