更新元素的数据属性jQuery

huangapple go评论51阅读模式
英文:

jQuery update data attr for element

问题

以下是翻译好的部分:

<div class="items">
    <div class="item" data-index="3"></div>
    <div class="item" data-index="3"></div>
    <div class="item" data-index="3"></div>

    <div class="item" data-index="6"></div>
    <div class="item" data-index="6"></div>
    <div class="item" data-index="6"></div>

    <div class="item" data-index="9"></div>
    <div class="item" data-index="9"></div>
    <div class="item" data-index="9"></div>
</div>

你提供的代码也有一个小错误,应该将 e 改成 i,这样才能正确地添加索引。修正后的代码如下:

$('.item').each(function(i) {
  $(this).attr('data-index', i);
})
英文:

So I have list of items and I need to add "data-index" for each element, index for first three elements have to be 3, for next 3 elements index have to be 6 ...

Should be something like this

&lt;div class=&quot;items&quot;&gt;
    &lt;div class=&quot;item&quot; data-index=&quot;3&quot;&gt;&lt;/div&gt;
    &lt;div class=&quot;item&quot; data-index=&quot;3&quot;&gt;&lt;/div&gt;
    &lt;div class=&quot;item&quot; data-index=&quot;3&quot;&gt;&lt;/div&gt;

    &lt;div class=&quot;item&quot; data-index=&quot;6&quot;&gt;&lt;/div&gt;
    &lt;div class=&quot;item&quot; data-index=&quot;6&quot;&gt;&lt;/div&gt;
    &lt;div class=&quot;item&quot; data-index=&quot;6&quot;&gt;&lt;/div&gt;

    &lt;div class=&quot;item&quot; data-index=&quot;9&quot;&gt;&lt;/div&gt;
    &lt;div class=&quot;item&quot; data-index=&quot;9&quot;&gt;&lt;/div&gt;
    &lt;div class=&quot;item&quot; data-index=&quot;9&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

Anyone have idea how to do it ?

I have this code which add numbers 0, 1, 2, 3, 4, 5...

$(&#39;.item&#39;).each(function(i) {
  $(this).attr(&#39;data-index&#39;,e)
})

答案1

得分: 0

$(&#39;.item&#39;).each(function(i) {
  var index = 3 * Math.floor(i / 3) + 3;
  $(this).attr(&#39;data-index&#39;, index);
});
英文:

Try this :

$(&#39;.item&#39;).each(function(i) {
  var index = 3 * Math.floor(i / 3) + 3;
  $(this).attr(&#39;data-index&#39;, index);
});

huangapple
  • 本文由 发表于 2023年2月6日 05:22:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75355610.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定