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

时间:2011-05-18 21:52:49

标签: jquery

这里小提琴: http://jsfiddle.net/F6nJu/

我有一个彩色的盒子:

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

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

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

我使用jQuery each()函数迭代这些颜色:

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

当数组迭代到最后时,我怎样才能开始数组迭代(所以动画会永远继续)?

4 个答案:

答案 0 :(得分:9)

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);

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

Live Example

对于那些对数组看起来感兴趣的人:

["#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.

答案 1 :(得分:5)

试试这个:

var arr = ["#f00", "#ff0", "#f0f", "#f66"];
$.each(arr, function(key, value) {
    set_color(value);
});

function set_color(color) {
    $('#colorblock').delay('1200').animate({
        backgroundColor: color
    }, 600);
    setTimeout(function() {
        set_color(color);
    }, 2000); //restart in 2 seconds
}

小提琴:http://jsfiddle.net/maniator/F6nJu/1/

答案 2 :(得分:2)

Array.prototype.recurse = function(callback, delay) {
   delay = delay || 200; 
   var self = this, idx = 0;

   setInterval(function() {
      callback(self[idx], idx);
      idx = (idx+1 < self.length) ? idx+1 : 0;
   }, delay);
}

在StackOverFlow上尝试:

["#f00", "#ff0", "#f0f", "#f66"].recurse(function(item, index) { 
    $('body').css('background-color', item);
}, 300);

答案 3 :(得分:0)

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

(function recurse(counter) {
    var arrLength = arr.length;
    var index = counter%arrLength;

    var color = arr[index];

    $('#colorblock').delay('1200').animate({
       backgroundColor: color
     }, 600);

    setTimeout(function() {
       recurse(counter + 1);
    }, 200);

})(0);