2012-10-18 51 views
0

我搜索了谷歌,並沒有找到一個簡單的解決方案。我無法弄清楚如何點擊一個數組

這裏是我的代碼JIST:

var theArray = ["one","two","three","four"]; 


    $('.next').click(function(){ 
    // go forward on the array 
    }) 

    $('.back').click(function(){ 
    // do backwards on the array from the current position 
    }) 

所以,如果用戶點擊"<button class="next">我會得到的「一」的警報,他們點擊「下一步」再一次,兩個」警報「等等......

有沒有一種快速的方法來做到這一點?

回答

4

你需要第二個變量來跟蹤你的指標:

var theArray = ["one","two","three","four"]; 
var arrayIndex=0; 

     $('.next').click(function(){ 
     arrayIndex++ 
     if(arrayIndex>=theArray.length) 
       arrayIndex=0; 
     alert(theArray[arrayIndex]); 
     }) 

     $('.back').click(function(){ 
     arrayIndex-- 
     if(arrayIndex<0) 
       arrayIndex=theArray.length-1; 
     alert(theArray[arrayIndex]); 
     }) 
+0

BRILLIANT!完美的作品。 – jake

5

肯定的:

theArray.push(theItem = theArray.shift()); 
// and... 
theArray.unshift(theItem = theArray.pop()); 

theItem是第一個和最後一個項目分別。重複調用該功能將繼續循環這些項目。

但是請注意,您不能再像「添加到另一端」一樣。要做到這一點,您需要手動跟蹤「當前項目」,然後增加/減少它,而不是循環周圍的項目。

+0

原諒的愚蠢,但我是什麼警示呢?你能詳細解釋一下嗎? – jake

+0

我會去挖掘什麼.push(),.shift(),.unshift(),&& .pop().. – jake