2017-09-20 38 views
1

我試圖編寫一個點擊函數來顯示jquery中的點擊函數上的下一個數組項,但它沒有工作。請指點:)點擊顯示下一個數組項目

var array = [one, two, three, four, five]; 
 
    
 
    $('#countButton').click(function(){ 
 
     for(var i = 0; i < array.length; i++){ 
 
     $('#displayCount').html(array[i++]);   
 
     }  
 
     });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 

 

 
<input type="button" value="Count" id="countButton" /> 
 
<p>The button was pressed <span id="displayCount">0</span> times.</p>

+1

不循環。將您的計數器存儲在單擊事件之外並在設置html後增加它 – Sysix

回答

0

沒有必要在這裏使用一個循環。單擊後訪問陣列中的下一個元素:

var array = ['one', 'two', 'three', 'four', 'five']; 
    var count = 0; 
    $('#countButton').click(function(){ 
    if(count <= array.length){ 
     count++; 
    } else{ 
     count = 0 
    } 
    $('#displayCount').html(array[count]);     
    }); 
+0

此代碼不起作用。 –

+0

現在它會...... – clearshot66

0

您不需要循環它。只是有一個全局變量使用相同的增量方法

var array = ['one', 'two', 'three', 'four', 'five']; 
 
var i = 0; 
 
$('#countButton').click(function() { 
 
    $('#displayCount').html(array[i++%5]); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 

 

 
<input type="button" value="Count" id="countButton" /> 
 
<p>The button was pressed <span id="displayCount">0</span> times.</p>

+0

當我變得比數組大小更大時會發生什麼?它會打破 – clearshot66

+0

立即檢查。現在它將再次從一個開始。你可以隨時改變它,它非常靈活 – jafarbtech

+0

What'[i ++%5]'意思是什麼。我知道'我++'但我不知道'%5'。 –

相關問題