我认为这与嵌套函数有关,但它们必须是这样的。为什么它不起作用?我在做傻事吗?这是一个孤立的示例,我必须使用 $(this)
,所以我似乎必须嵌套函数?
HTML:
<div class="box"></div>
<ul>
<li>Hover box, it turns blue. Leave box, it turns red after 2 secs.</li>
<li>If you hover back onto box before 2 secs is up, it's supposed to clear timer and keep box blue.</li>
<li>It doesn't clear timer and after 2 secs the box still turns red. Why?</li>
</ul>
JavaScript:
var t;
$('.box').on('mouseenter', function() {
$thisBox = $(this);
clearTimeout(t);
$thisBox.addClass('blue');
$thisBox.on('mouseleave', function() {
t = setTimeout(function() { $thisBox.removeClass('blue'); }, 2000);
})
});
JSFiddle: http://jsfiddle.net/ddbtZ/7/
感谢观看:)
最佳答案
您的 .on()
不应嵌套。实际上,每次将鼠标悬停在元素上时,都会附加一个新的处理程序。
编辑:根据问题说明。
使用.one()
代替.on()
关于javascript - clearTimeout 在嵌套函数中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10889785/