我认为这与嵌套函数有关,但它们需要这样。为什么它不起作用?我在做傻事吗?这是一个孤立的例子,我必须使用$(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/
谢谢你看:)