jQuery显示/隐藏列表中的每个元素

时间:2016-11-28 21:36:25

标签: javascript jquery

问题在于我想为列表中的每个名称更改innerHTML属性,并使用(fadeIn,延迟x秒,fadeOut)为其设置动画

<div id="welcomeBox">Welcome SOMETHING</div>

var list = ["George","Bob","Tom"];

$.each(list, function()
{
    $("#welcomeBox")
        .eq(0)
        .text('Welcome' + this)
        .fadeToggle(1500)
        .delay(5000)
        .fadeToggle(1500);
});

使用上面的代码我只得到3x Welcome Tom消息。

1 个答案:

答案 0 :(得分:2)

var list=["George","Bob","Tom"];

// recursive closure to iterate thru list
(function recurse(index){
    // on fade use the callback to fade out
    $("#welcomeBox").text('Welcome ' + list[index]).fadeIn(1500, function(){
        $("#welcomeBox").fadeOut(1500, function(){
            // after fade out, call the function again with the next index
            recurse(undefined !== list[index+1] ? index+1 : 0);
        });
    });
})(0);

https://jsfiddle.net/6qo0L6mr/