[英]setTimeout function is not called
在你跳到重复的问题之前,我必须说我在来到这里之前已经浏览了 stackoverflow 和其他地方。
所以基本上,我使用的是一个精灵图像并且需要遍历其中的图像。 在下面的代码块中,您将找到我现在处理它的方式。 但是,在添加setTimeout
函数后,似乎不再执行函数参数中的所有内容。
var headerTimeout = 1000/24;
jQuery('.headerGif').hover(function(){
for(var i = 1; i <= 41; i++){
setTimeout(function(){
if (jQuery(this).hasClass('.header-HeaderBedrijfsVideo00' + (i - 1))) {
jQuery(this).removeClass('.header-HeaderBedrijfsVideo00' + (i - 1));
}
jQuery(this).addClass('.header-HeaderBedrijfsVideo00' + i);
}, headerTimeout);
}
});
如果有更好的方法来解决这个问题,如果有人能指出我正确的方向,我将不胜感激。 我已经在考虑为此目的使用插件。
编辑:我试过检查重复标记中的问题,但这基本上是闭包的作用,不是吗? 我刚刚从其中一个答案中添加了闭包,但它仍然不起作用。
使用闭包,for 循环将在超时函数之前执行,然后您可以获得最后递增的 i 值 41,因此在这种情况下,您必须像多线程一样使用闭包
jQuery('.headerGif').hover(function () {
var _this=this;
for (var i = 1; i <= 41; i++) {
(function (i) {
setTimeout(function () {
if (jQuery(_this).hasClass('.header-HeaderBedrijfsVideo00' + (i - 1))) {
jQuery(_this).removeClass('.header-HeaderBedrijfsVideo00' + (i - 1));
}
jQuery(_this).addClass('.header-HeaderBedrijfsVideo00' + i);
}, i*100);
})(i);
}
});
原因
for
循环的结尾是什么)!!查看下面的小提琴(检查控制台)
http://jsfiddle.net/szx19hzo/2/
.
在 hasClass 函数中您可以删除超时以使其工作,请检查以下链接(检查控制台和检查元素以注意该类已被删除)
http://jsfiddle.net/szx19hzo/3/
解决方案
如果要保留超时,则使用不同的函数并在循环内调用它,并在函数内部给出超时如果要保留超时,请使用以下解决方案
http://jsfiddle.net/szx19hzo/4/
var headerTimeout = 1000/24;
jQuery('.headerGif').hover(function(){
for(var i = 1; i <= 41; i++){
var className='header-HeaderBedrijfsVideo00' + (i - 1);
removeClass(this,className,i);
}
});
function removeClass(item,className,i){
setTimeout(function(){
console.log(className);
if (jQuery(item).hasClass(className)) {
jQuery(item).removeClass('header-HeaderBedrijfsVideo00' + (i - 1));
console.log("removed");
}
jQuery(item).addClass('.header-HeaderBedrijfsVideo00' + i);
}, headerTimeout);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.