【问题标题】:Display next array items on click单击时显示下一个数组项
【发布时间】:2018-03-02 00:30:57
【问题描述】:

我尝试编写一个点击函数来在 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>

【问题讨论】:

  • 不要循环。将您的计数器存储在点击事件之外,并在设置 html 后增加它

标签: jquery arrays for-loop


【解决方案1】:

这里没有必要使用循环。单击后只需访问数组中的下一个元素:

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

【讨论】:

    【解决方案2】:

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

    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>

    【讨论】:

    • 当 i 大于数组大小时会发生什么?会坏的
    • 现在检查。现在它将再次从一个开始。你可以随心所欲地改变它,它是如此灵活
    • [i++%5] 是什么意思。我知道i++,但我不知道%5
    • 取模运算,除以5得到余数
    • 我明白了,但为什么我需要使用它?
    猜你喜欢
    • 2020-12-09
    • 2014-11-28
    • 2020-10-12
    • 2015-01-12
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多