在"for"循环中使用Jquery promise()等待效果完成,然后再开始下一个效果
我想知道为什么下面的代码在开始循环中的下一个动画之前不等待动画完成.
I want to know why the following code does not wait for an animation to finish before starting the next animation in the loop.
由于某种原因,循环创建的所有元素会立即显示并同时淡入.从代码中,我希望第一个元素将在循环的第一次迭代完成之前逐渐消失,然后"for"循环的第二次迭代将在下一个元素中逐渐消失,依此类推.
For some reason all the elements created by the loop are displayed at once and faded in simultaneously. From the code, I would expect that the first element would finish fading in before the first iteration of the loop finishes then the second iteration of the 'for' loop would fade in the next element and so on..
在创建混乱的代码之前,我不想使用回调,而且我想使用将使用动态数据的循环-动画的数量会有所不同.
I do not want to use callbacks before this creates messy code and also I want to use a loop which will use dynamic data -- the number of animations will vary.
<div id="container"></div>
<script>
var data = [1,2,3,4];
for(var i = 0; i < data.length; i++){
$("#container").append("<h1>"+data[i]+"</h1>").hide().show("fade",2000);
$("#container").promise().done(function(){console.log('sweet');});
}
</script>
Promise不会神奇地终止您的for
循环,它们所做的只是提供一种链接回调的方法.您一次要制作所有动画,然后等待它们同时完成.要按顺序获取它们,可以使用
Promises do not magically halt your for
loop, all they do is provide a way to chain callbacks. You were doing all your animations at once, and waited for them concurrently to finish. To get them in sequence, you can use
<div id="container"></div>
<script>
[1,2,3,4].reduce(function(prev, d, i) {
return prev.then(function() {
console.log('start', i)
return $("<h1/>", {text: d})
.appendTo("#container")
.hide().show("fade",2000) // I assume you meant to animate the h1, not the container
.promise();
}).then(function() {
console.log('sweet! end', i);
});
}, $.when());
</script>