循环遍历每个元素并按顺序打印值

时间:2018-02-09 14:51:31

标签: javascript jquery

我有一些代码,我想循环遍历元素的数量,并将每个文本中的文本从1开始设置为有多少。我的方法如下:

$(function() {
  var items = $(".item");
  items.each(function(i) {
    var itemCount = i + 1;
    items.text(itemCount);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<span class="item"></span>
<span class="item"></span>
<span class="item"></span>
<span class="item"></span>
<span class="item"></span>
<span class="item"></span>

然而,它打印总数为6次。在这个具体的例子中,6。

我理解.each()的方式是它单独迭代每个元素,我的想法是我能够传递itemCount的值并让它分别计算每个元素。如果我做了一个普通的vanilla JS循环,那么片段中的结果将有意义,因为它在打印之前完成。

如何更改此方法以按顺序打印数字(1 2 3 4 5 6)而不是元素总数6次?

3 个答案:

答案 0 :(得分:4)

您必须使用<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:maxLines="1" android:text="Sample text" android:textAllCaps="false" /> <Button android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:maxLines="1" android:text="Extra text" android:textAllCaps="false" /> </LinearLayout> 作为this之类的选择器。 $(this)引用每个循环上的元素。

目前,您正在使用this引用所有类别为items

的html元素

&#13;
&#13;
.item
&#13;
$(function() {
  var items = $(".item");
  items.each(function(i) {
    var itemCount = i + 1;
    $(this).text(itemCount);
  });
});
&#13;
&#13;
&#13;

答案 1 :(得分:4)

问题是因为items引用所有元素,因此您在每次迭代中更新它们中的每一个。要解决此问题,您可以使用this关键字来引用each()循环中的当前实例。

更好的是,您可以为text()方法提供一个函数,并使用提供给处理函数的第一个参数,该函数是元素的索引。这样你根本不需要显式循环或对元素的引用。试试这个:

&#13;
&#13;
$(".item").text(function(i) {
  return ++i;
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<span class="item"></span>
<span class="item"></span>
<span class="item"></span>
<span class="item"></span>
<span class="item"></span>
<span class="item"></span>
&#13;
&#13;
&#13;

答案 2 :(得分:2)

items设置为$(".item");,因此您需要使用$(this)确定要使用的项目

&#13;
&#13;
$(function() {
  var items = $(".item");
  items.each(function(i) {
    var itemCount = i + 1;
    $(this).text(itemCount);
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<span class="item"></span>
<span class="item"></span>
<span class="item"></span>
<span class="item"></span>
<span class="item"></span>
<span class="item"></span>
&#13;
&#13;
&#13;

相关问题