jquery 函数 setInterval
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6693157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery function setInterval
提问by callum.bennett
$(document).ready(function(){
setInterval(swapImages(),1000);
function swapImages(){
var active = $('.active');
var next = ($('.active').next().length > 0) ? $('.active').next() : $('#siteNewsHead img:first');
active.removeClass('active');
next.addClass('active');
}
});
I have 13 images contained in a div. The first one has a class called active, which means it is displayed.
我有 13 张图片包含在一个 div 中。第一个有一个名为 active 的类,这意味着它被显示。
The swap images function selects the active image and hides it, and makes the next image active.
交换图像功能选择活动图像并将其隐藏,并使下一个图像处于活动状态。
However, when the page loads, the function only works correctly once, rather than looping.
但是,当页面加载时,该功能只能正常工作一次,而不是循环。
Any ideas?
有任何想法吗?
回答by Nicola Peluchetti
This is because you are executing the function not referencing it. You should do:
这是因为您正在执行该函数而不是引用它。你应该做:
setInterval(swapImages,1000);
回答by FishBasketGordo
Don't pass the result of swapImages
to setInterval
by invoking it. Just pass the function, like this:
不要通过调用swapImages
来传递to的结果setInterval
。只需传递函数,如下所示:
setInterval(swapImages, 1000);
回答by Rajkumar
// simple example using the concept of setInterval
// 使用 setInterval 概念的简单示例
$(document).ready(function(){
var g = $('.jumping');
function blink(){
g.animate({ 'left':'50px'
}).animate({
'left':'20px'
},1000)
}
setInterval(blink,1500);
});
回答by zevy_boy
try this declare the function outside the ready event.
试试这个在就绪事件之外声明函数。
$(document).ready(function(){
setInterval(swapImages(),1000);
});
function swapImages(){
var active = $('.active');
var next = ($('.active').next().length > 0) ? $('.active').next() : $('#siteNewsHead img:first');
active.removeClass('active');
next.addClass('active');
}
回答by ashvagan
You can use it like this:
你可以这样使用它:
$(document).ready(function(){
setTimeout("swapImages()",1000);
function swapImages(){
var active = $('.active');
var next = ($('.active').next().length > 0) ? $('.active').next() : $('#siteNewsHead img:first');
active.removeClass('active');
next.addClass('active');
setTimeout("swapImages()",1000);
}
});
});