setTimeout仍会触发,尽管已经clearTimeout。

3

我有以下功能。目的是当你悬停在一个类为.toolTip的元素上时,它将在3秒后记录你正在悬停的元素的data-tooltip。然而,如果你的光标离开了该元素,它应该取消setTimeout并不显示消息。

"Timeout set"和"Timeout cleared"消息按预期触发,但命名的函数仍会触发。我做错了什么?

$(document).on("hover",".toolTip", function() {
    var toolTip = $(this);
    var toolTipMessage
    var hoveringNow = toolTip.attr("data-hovering-now");
    if(typeof hoveringNow !== typeof undefined && hoveringNow !== false) {
        toolTip.removeAttr('data-hovering-now');
        clearTimeout(toolTipMessage);
        console.log('Timeout cleared');
    }
    else {
        toolTip.attr('data-hovering-now', true);
        toolTipMessage = setTimeout(showToolTip, 3000, toolTip.attr("data-tooltip"));
        console.log('Timeout set');
    }               
});

function showToolTip(message) {
    console.log(message);
}

2
var toolTipMessage 放在 hover 函数处理程序之外,否则您会在每个事件上重新定义它。我也有点困惑于使用 hovering-now 数据属性来保留状态的目的,为什么不只是使用两个处理程序函数?一个用于 mouseenter,另一个用于 mouseleave - Rory McCrossan
1个回答

3

你的变量toolTipMessage仅存在于执行悬停操作的函数的执行上下文中,当你再次悬停在该元素上时,该变量将不再存在(或者更准确地说,你拥有一个相同名称的不同的变量)。

为了使变量在执行之间保持持久性,你需要将该变量定义在封闭的执行上下文中 - 例如在hover处理程序之外。

var toolTipMessage = null;
$(document).on("hover",".toolTip", function() {
   ....
});

啊哈!谢谢,你说了之后现在完全明白了。 - Sinister Beard
1
不同的“执行上下文”是我认为的术语。 - Jeff P Chacko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接