我已经在我正在努力解决的一段代码上得到了一些很好的帮助。希望有人可以再次帮助我。我的代码在点击后5秒显示项目旁边的复选标记。问题:如果用户快速点击链接,我需要取消弹出复选标记。这是演示:
这是代码。我从几个人那里得到了一些帮助,但Timeout仍然没有工作:
$(function() {
var thetimeout=null;
$('li a').click(function() {
$('li').not('this').css('background-position','left bottom');
$(this).parent().css('background-position','left top');
if(thetimeout!=null) {
window.clearTimeout(thetimeout);
}
var thetimeout=window.setTimeout($.proxy(function() {
$(this).parent().css('background-image','url(images/check.png)');
}, this)
,5000);
});
});
clearTimeout应该取消所有未被点击的元素的超时但它不起作用......任何想法?
答案 0 :(得分:1)
您设置的超时在click事件中存在于本地 - 因此每次点击事件都存在它自己的超时。
将var thetimeout
移到$('li').click
之前,然后在click事件中使用thetimeout=
(因为此处有另一个var在本地范围内定义了一个新变量,而不是使用先前的一个)。
此外,根据您的使用情况,您可能需要先检查超时是否已存在if ( !thetimeout )
,然后再设置新超时,以及始终在调用clearTimeout(thetimeout)
后应该执行此操作thetimeout = null
否则变量可能仍然有值。
由于上述建议可能会产生混淆的空间,因此附带的代码附有建议:
$(function() {
// Define our Timeout
var thetimeout=null,
clearTheTimeout = function(){
if ( thetimeout ) {
window.clearTimeout(thetimeout);
}
thetimeout = null;
};
// Do our Click
$('li a').click(function() {
$('li').not('this').css('background-position','left bottom');
$(this).parent().css('background-position','left top');
// Clear the Timeout
clearTheTimeout();
// Set the Timeout
thetimeout = window.setTimeout(
$.proxy(function(){
$(this).parent().css('background-image','url(images/check.png)');
clearTheTimeout();
},this)
,5000);
});
});