以下代码块有一些问题:
$('.merge').each(function(index) {
var mergeEl = $(this);
setTimeout(function() {
self.mergeOne(mergeEl, self, index - (length - 1));
}, 500);
});
我试图在每次 mergeOne
调用之间应用 0.500 秒延迟,但此代码仅在调用 mergeOne
之前应用 0.500 秒延迟数组中的元素。
如果有人可以解释为什么此代码不起作用,并且可能是一个很棒的可行解决方案,谢谢!
最佳答案
这是一个通用函数,可用于迭代 jQuery 对象的集合,每次迭代之间有延迟:
function delayedEach($els, timeout, callback, continuous) {
var iterator;
iterator = function (index) {
var cur;
if (index >= $els.length) {
if (!continuous) {
return;
}
index = 0;
}
cur = $els[index];
callback.call(cur, index, cur);
setTimeout(function () {
iterator(++index);
}, timeout);
};
iterator(0);
}
演示: http://jsfiddle.net/7Ra9K/ (循环一次)
演示: http://jsfiddle.net/42tXp/ (连续循环)
传递给回调的上下文和参数应该与 .each()
的处理方式相同。
如果你想让它成为一个 jQuery 插件,那么它可以像 $("selector").delayedEach(5000, func...
这样调用,那么你可以使用这个:
$.fn.delayedEach = function (timeout, callback, continuous) {
var $els, iterator;
$els = this;
iterator = function (index) {
var cur;
if (index >= $els.length) {
if (!continuous) {
return;
}
index = 0;
}
cur = $els[index];
callback.call(cur, index, cur);
setTimeout(function () {
iterator(++index);
}, timeout);
};
iterator(0);
};
演示: http://jsfiddle.net/VGH25/ (循环一次)
演示: http://jsfiddle.net/NYdp7/ (连续循环)
更新
我添加了连续遍历元素的能力,作为一个额外的参数。传递 true
将连续循环,而传递 false
或什么都不传递(或一些错误的东西)只会在元素上循环一次。代码和 fiddle 包括更改。
关于javascript - 在 jQuery 的 .each() 方法的每次迭代之间应用延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18166854/