javascript - clearTimeout 在嵌套函数中不起作用

标签 javascript jquery nested settimeout

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

感谢观看:)

最佳答案

http://jsfiddle.net/ddbtZ/3/

您的 .on() 不应嵌套。实际上,每次将鼠标悬停在元素上时,都会附加一个新的处理程序。

编辑:根据问题说明。

使用.one()代替.on()

http://jsfiddle.net/ddbtZ/8/

关于javascript - clearTimeout 在嵌套函数中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10889785/

相关文章:

javascript - HTML5 DataList 是否有 SelectedIndex?

javascript - Handlebars.js 和链接标签

javascript - 谷歌地图网络服务在本地工作但不在线

python - 如果我使用派生类,我可以 "pickle local objects"吗?

javascript - 带确认框的 Data.gui.js 明文

javascript - 想要使用 jquery 单击特定按钮时禁用我的复选框(变灰)

javascript - 面对错误 "',此'隐式具有类型 'any',因为它没有类型注释”在 typescript 中调用 REST API 时

loops - 在 gnuplot 4.6 中循环多个语句的优雅方法?

jquery - 循环嵌套对象

javascript - 通过 jQuery 更改 src 值