以连续方式执行循环中的所有元素?

时间:2014-09-06 17:16:58

标签: javascript jquery css

如何在循环中执行函数,使循环中的下一个元素仅在前一个元素完成时执行。

$(".welcome>p").each(function() {
    var $this = $(this);
    setTimeout(function() {
        $this.animate({
            opacity: 1
        }, 600);
    });

});

因此,此代码中的所有p元素将同时运行。如何更改它以便p元素按顺序逐个显示?

谢谢, YonL

1 个答案:

答案 0 :(得分:3)

each的第一个参数是index,因此您可以使用该索引来增加setTimeout,如:

$(".welcome>p").each(function( idx ) {
    var $this = $(this);
    setTimeout(function() {
        $this.animate({
            opacity: 1
        }, 600);
    }, idx * 600);

});