简体   繁体   中英

Iterating through a jQuery array

I'm trying to iterate through an array and assign values to an element as such:

<tool>hammer</tool>

var tools = ["screwdriver", "wrench", "saw"];
var i;
for (i=0; i < tools.length; ++i){
$("tool").delay(300).fadeOut().delay(100).html(tools[i]).fadeIn();
};

However this doesn't seem to work as only "saw" is assigned as the html value and keeps fading in and out.

What am I doing wrong here?

jQuery.delay() pauses between effects queued items , so your .html() is being set instantaneously. Hence, you only see saw .

A solution is to scrap the for loop and "loop" against the length of the array, setting the tool text to the next first item in the array (as you remove it). However, you need to do this inside the context of the queue, so you can use the .fadeOut() callback to do this.

Wrap all this in a function (here, I immediately invoke it but give it a label, a , so it can be referenced, it's not anonymous ) and pass that to .fadeIn() at the end so it continues the loop until the array is empty.

var tools = ["screwdriver", "wrench", "saw"];

(function a(){
    if (tools.length) {
        $("tool").delay(300).fadeOut(0, function(){
            $(this).html(tools.shift());
        }).delay(100).fadeIn(a);
    }
})();

http://jsfiddle.net/tc1q1vv7/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM