我有以下功能。其意图是,当您将鼠标悬停在类别为.toolTip
的项目上时,它会在3秒后从您悬停的元素中记录data-tooltip
。但是,如果您的光标离开了该项目,它应该取消setTimeout并且不显示该消息。setTimeout尽管clearTimeout仍然会触发
“超时设置”和“超时已清除”消息按预期启动,但指定的函数仍会触发。我究竟做错了什么?
$(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);
}
将'var toolTipMessage'放在'hover'函数处理程序之外,否则在每个事件上重新定义它。对于保留状态的'hovering-now'数据属性,我也有点困惑,为什么不使用这两个处理函数呢?一个用于mouseenter,另一个用于mouseleave? –