【问题标题】:how to ADD class in every to div using loop如何使用循环将每个类添加到 div
【发布时间】:2021-11-24 03:47:49
【问题描述】:

这是我的结构我想在每两个 div 中添加奇偶类所以我如何使用 JavaScript 循环来实现这个结构我尝试了一切但我什么也没得到我正在学习 JavaScript 循环所以请任何人帮助我

var i = 0;
$('.CollectionInner__Products .Grid__Cell .ProductItem').each(function(i) {
  var index = 0;
  if (index % 3 == 0) {
    $(this).addClass("odd");
  }
});
<div class="custompsps">
  <div class="ProductItem">
  </div>
  <div class="ProductItem">
  </div>
  <div class="ProductItem">
  </div>
  <div class="ProductItem">
  </div>

</div>
<div class="custompsps">
  <div class="ProductItem">
  </div>
  <div class="ProductItem">
  </div>
  <div class="ProductItem">
  </div>
  <div class="ProductItem">
  </div>

</div>

我想要这个结构:

i want this stucture
<div class="custompsps">
  <div class="ProductItem even">
  </div>
  <div class="ProductItem even">
  </div>
  <div class="ProductItem odd">
  </div>
  <div class="ProductItem odd">
  </div>

</div>
<div class="custompsps">
  <div class="ProductItem even">
  </div>
  <div class="ProductItem even">
  </div>
  <div class="ProductItem odd">
  </div>
  <div class="ProductItem odd">
  </div>

</div>

【问题讨论】:

  • 在您的循环中,您可以使用if (i % 4 &lt; 2) 测试当前迭代是在一对中的前两个还是后两个中,并使用它来决定添加哪个类。
  • 请展示您的最佳尝试,我们会帮助您修复它,我们不会为您编写代码。
  • var i=0; $('.CollectionInner__Products .Grid__Cell .ProductItem').each(function(i){ var index = 0; if(index % 3 == 0) { $(this).addClass("odd"); } });
  • 你每次都将索引设置为0,为什么index % 3会改变?你为什么使用%3?这告诉你索引是否是 3 的倍数,这与对无关。
  • 请问在课堂上加偶数和奇数的目的是什么?这可能是 XY 问题,可以使用 CSS 选择器解决?

标签: javascript html jquery css


【解决方案1】:
$('.CollectionInner__Products .Grid__Cell .ProductItem').each(function(index, element) {
  $(element).addClass(index & 2 ? "even" : "odd");
});

&amp; 是一个bitwise "and"index &amp; 2 将是 0 用于索引 0 和 1,2 用于索引 2 和 3,像这样交替。 0 是假的,非0 是真的。 (您对“偶数”和“奇数”的使用似乎是倒退的,但我遵循了您的使用方法。)

jQuery 的 .each 接受一个回调,该回调可以接受索引和元素参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    • 2012-02-03
    • 2021-02-28
    • 1970-01-01
    相关资源
    最近更新 更多