单击显示下一个数组项

时间:2017-09-20 19:47:46

标签: jquery arrays for-loop

我尝试编写一个单击函数来显示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>

2 个答案:

答案 0 :(得分: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]);                 
   });

答案 1 :(得分:0)

你不需要循环它。只需要一个全局变量使用相同的增量方法

&#13;
&#13;
var array = ['one', 'two', 'three', 'four', 'five'];
var i = 0;
$('#countButton').click(function() {
  $('#displayCount').html(array[i++%5]);
});
&#13;
<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>
&#13;
&#13;
&#13;