jquery循环遍历数组和反向

时间:2013-12-06 13:03:22

标签: javascript jquery css

如何循环显示这个数组,它会按时间顺序更改css背景颜色,而不是随机翻转,并在单击后退按钮时反转同一个数组?

http://jsfiddle.net/qK2Dk/

$('#right').click(function(){

var bgImages = ["#fff", "#f00", "#000", "#f0f", "#ccc", "#ddd", "#eee", "#bbb"];
var bgImage = bgImages[Math.floor(Math.random() * bgImages.length)];
var image = bgImage;

var element = document.getElementById('bgImage');
element.style.background  = image; // IE fallback

});


<a class="left carousel-control" id="left" href="#carousel" data-slide="prev">
<span>Left</span>
</a>
<br />
<a class="right carousel-control" id="right" href="#carousel" data-slide="next">
<span>Right</span>
</a>

<div id="bgImage">
test
</div>

1 个答案:

答案 0 :(得分:1)

试试这个

var ix=0;
$('#right').click(function(){

    var bgImages = ["#fff", "#f00", "#000", "#f0f", "#ccc", "#ddd", "#eee", "#bbb"];
    var bgImage = bgImages[ix];
    if(ix<bgImages.length){
         ix++;
    }

    var image = bgImage;
    var element = document.getElementById('bgImage');
    element.style.background  = image; // IE fallback

});

$('#left').click(function(){

    var bgImages = ["#fff", "#f00", "#000", "#f0f", "#ccc", "#ddd", "#eee", "#bbb"];
    if(ix>0){
         ix--;
    }
    var bgImage = bgImages[ix];


    var image = bgImage;
    var element = document.getElementById('bgImage');
    element.style.background  = image; // IE fallback

});

<强> DEMO