jQuery:通过数组的无限循环... each()?

问题描述:

在这里拨弄: http://jsfiddle.net/F6nJu/

我有一个彩色框:

<div id="colorblock"></div>
#colorblock { background:#3ff; width: 100%; height: 300px; }

我在javascript中创建了一系列颜色:

I have an array of colors created in javascript:

var arr = [ "#f00", "#ff0", "#f0f", "#f66"];

我使用jQuery each()函数遍历这些颜色:

I iterate through those colors with a jQuery each() function:

$.each(arr, function(key, value) {
  $('#colorblock').delay('1200').animate({backgroundColor:value}, 600);
});

当数组迭代到最后时,如何重新开始数组迭代(这样动画会一直持续下去)?

When the array iterates to the end, how can I start the array iteration over (so the animation goes on forever)?

var arr = ["#f00", "#ff0", "#f0f", "#f66"];

// run through the array forever
(function recurse(counter) {
    // get the colour
    var color = arr[counter];
    // animate it
    $('#colorblock').delay('1200').animate({
        backgroundColor: color
    }, 600);
    // delete the value to save memory
    delete arr[counter];
    // add the value at the end of the array
    arr.push(color);
    // run it again for the next number
    setTimeout(function() {
        recurse(counter + 1);
    }, 200);
// start it for the first number.
})(0);

无限递归.删除当前条目,然后将当前值添加到末尾.

Infinite recursion. Delete the current entry, then add the current value to the end.

Live Example

对于那些对数组的外观感兴趣的人:

For those who are interested in what the array looks like:

["#foo", "#ff0", "#f0f", "#f66"] (counter = 0)
[undefined, "#ff0", "#f0f", "#f66", "#foo"] (counter = 1)
[undefined, undefined, "#f0f", "#f66", "#foo", "#ff0"] (counter = 2)
[undefined, undefined, undefined, "#f66", "#foo", "#ff0", "#f0f"] (counter = 3)
[undefined, undefined, undefined, undefined, "#foo", "#ff0", "#f0f", "#f66"] (counter = 4)
etc.