Jquery selector.each:如何一次遍历列表x?

时间:2018-03-02 04:33:26

标签: jquery

所以我有以下HTML

<ul>
  <li class="id id1-1">id1-1</li>
  <li class="id id1-2">id1-2</li>
  <li class="id id1-3">id1-3</li>
  <li class="id id2-1">id2-1</li>
  <li class="id id2-2">id2-2</li>
  <li class="id id2-3">id2-3</li>
  <li class="id id3-1">id3-1</li>
  <li class="id id3-2">id3-2</li>
  <li class="id id3-3">id3-3</li>
</ul>

我想一次迭代/处理3个项目。

类似:(不工作!)

$(".id").each(function(index){
    $(this).hide() //processes idx-1
    index=index+1; //move to idx-2

    $(this).hide() //processes idx-2
    index=index+1; //move to idx-3

    $(this).hide() //processes idx-3. on next iteration. each "pointer" is at 4th item.
});

有任何想法可以做到吗?

由于

1 个答案:

答案 0 :(得分:2)

只需使用for循环

&#13;
&#13;
$(function() {
  var li = $(".id");

  for (i = 0; i < li.length; i += 2) {
    console.log("================= " + i);
    console.log($(li[i]).text());
    console.log($(li[i + 1]).text());
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li class="id id1-1">id1-1</li>
  <li class="id id1-2">id1-2</li>
  <li class="id id1-3">id1-3</li>
  <li class="id id2-1">id2-1</li>
  <li class="id id2-2">id2-2</li>
  <li class="id id2-3">id2-3</li>
  <li class="id id3-1">id3-1</li>
  <li class="id id3-2">id3-2</li>
  <li class="id id3-3">id3-3</li>
</ul>
&#13;
&#13;
&#13;