【问题标题】:How can I use jQuery's each and click method?如何使用 jQuery 的 each 和 click 方法?
【发布时间】:2016-08-09 04:36:54
【问题描述】:

如果单击按钮,我想在数组中切换文本。

(text[0] -> text[1] -> text[2] -> text[0])

如果到达数组索引的末尾,则再次返回数组中索引的开始。(循环)

我认为使用 each 和 click 方法。 但每种方法都适用。

我该怎么做?

这是我的代码

$(document).ready(function() {
  var arr = ["uno", "dos", "tre"];
  $("button").click(fuction() {
    $.each(arr, function() {
      $("p").text(arr);
    });
  });
});

【问题讨论】:

  • 如果您的答案已解决,请接受答案。

标签: jquery arrays indexing click each


【解决方案1】:

像这样,JSFiddle

$(document).ready(function() {
  var arr = ["uno", "dos", "tre"];
  var arrIndex = 0;
  $("button").click(function() {
      $("p").text(arr[arrIndex++]);
      arrIndex = arrIndex % arr.length;
  });
});

您不需要每个循环。为数组中的项目保留一个索引,并增加它。

【讨论】:

  • 非常感谢!!我从来不知道 (` arrIndex = arrIndex % arr.length; `) !
  • @user14661,当您提出问题并收到可接受的答案时,您应该单击答案左侧的复选标记以接受它。
【解决方案2】:

试试这个代码:

 $(document).ready(function() {

 var arr = ["uno", "dos", "tre"];
 var count=0;
 var n=arr.length;

 $("button").click(function() {

   count+=1;
   $("p").text(arr[count%n]);


 });

});

【讨论】:

  • 只输入数字时要小心。在这种情况下,您的2,数字实际上应该是 3,但数组的大小可能并不总是相同,因此更有意义的是使用数组的大小。另外,您错过了 OP 在“function”的拼写中犯的错误。
猜你喜欢
  • 2017-06-07
  • 2012-12-13
  • 2016-08-20
  • 1970-01-01
  • 2011-01-20
  • 2011-07-02
  • 2013-09-28
  • 1970-01-01
  • 2021-04-30
相关资源
最近更新 更多