gpt4 book ai didi

javascript - 清除 JS 中的计时器的问题

转载 作者:行者123 更新时间:2023-11-29 10:41:32 24 4
gpt4 key购买 nike

我有一些使用 PHP 动态创建的元素。我希望用户将鼠标悬停在一个图标上并显示相应的元素。当鼠标离开图标时,我希望计时器启动然后隐藏该元素。如果鼠标进入显示的元素,我想清除计时器。当鼠标离开该元素时,我希望计时器重新开始。

我很难弄清楚这一点,我无法弄清楚为什么计时器不会清除。以下所有 jQuery 都在 document.ready 中。

jQuery

var $infoIcon = $('.fa-info-circle');
var $trackListing = $('track-listing');
var timer;

// Show listing on hover
$infoIcon.on('mouseenter', function(){
$(this).next('.track-listing').fadeIn();
clearTimeout(timer);

// Start timer when exiting the info icon
}).on('mouseleave', function(){
timer = setTimeout(function(){
$('.track-listing').fadeOut();
}, 2000);
});

// Kill timer when entering listing box
$trackListing.on('mouseenter', function(){
clearTimeout(timer);

// Start timer when leaving listing box
}).on('mouseleave', function(){
timer = setTimeout(function(){
$('.track-listing').fadeOut();
}, 2000);
});

如果您需要 PHP,请告诉我。此外,我尝试将 var timer; 作为全局变量放在 document.ready 之外,我得到了相同的结果。

最佳答案

如果您在页面加载后插入元素,请尝试像这样绑定(bind)它们:

$(document).on(event, '.selector', function(){});

委托(delegate)事件

关于javascript - 清除 JS 中的计时器的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28112291/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com