javascript jquery each() 与 setInterval
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12588617/
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 each() with setInterval
提问by artparks
I have an object filled with various elements that I wish to iterate through using each()
and then perform an action on the element whose turn it is. So:
我有一个充满各种元素的对象,我希望通过使用进行迭代each()
,然后对轮到它的元素执行操作。所以:
var arts = $("#press-sqs > article");
shuffle(arts);
$(arts).each(function(){
setInterval(function() {
// in here perform an action on the current element in 'arts'
}, 2000);
});
( shuffle()
is a basic shuffle function )
(shuffle()
是一个基本的随机播放功能)
What I can't figure out is how to access the current element as a selector and perform an action on it. $(this)
is $(window)
.
我想不通的是如何将当前元素作为选择器访问并对其执行操作。$(this)
是$(window)
。
Finally I would then need the function to start the iteration again once it reaches the end of art
and keep on looping ad infinitum.
最后,一旦到达末尾art
并继续无限循环,我将需要该函数再次开始迭代。
回答by Eric
If you're using setInterval
, you'd get identical results swapping the order:
如果您使用setInterval
,则交换顺序会得到相同的结果:
setInterval(function() {
$(arts).each(function(){
doSomethingWith(this);
});
}, 2000);
I don't think you want what you think you do here. I reckon you want:
我不认为你想要你在这里做的事情。我想你想要:
var i = 0;
setInterval(function() {
var art = arts[i++];
doSomethingWith(art)
if(i >= arts.length) i = 0;
}, 2000);
回答by Will Palmer
jQuery's .each(...)
method passes the "current" element (and its index) into the callback. this
is just a convenience for when you don't need to do anything too complicated.
jQuery 的.each(...)
方法将“当前”元素(及其索引)传递到回调中。this
当您不需要做任何太复杂的事情时,这只是一种便利。
$(arts).each(function(i, current){
setInterval(function() {
// in here perform an action on the current element in 'arts'
}, 2000);
});
Above, the current element is available within the setInterval callback as current
, for example. Note that this element is passed in its "raw" form, as this
is, so if you want to call jQuery methods on it, you'll need to wrap it in the same way, ie: $(current)
.
上面,当前元素在 setInterval 回调中可用current
,例如。请注意,此元素以其“原始”形式传递this
,因此,如果您想在其上调用 jQuery 方法,则需要以相同的方式包装它,即:$(current)
。
回答by Vlad
Use that.
用那个。
$(arts).each(function(){
var that = this;
setInterval(function() {
// in here perform an action on the current element in 'arts'
doSomethingWith(that)
}, 2000);
});