英文:
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
<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>
Anyone have idea how to do it ?
I have this code which add numbers 0, 1, 2, 3, 4, 5...
$('.item').each(function(i) {
$(this).attr('data-index',e)
})
答案1
得分: 0
$('.item').each(function(i) {
var index = 3 * Math.floor(i / 3) + 3;
$(this).attr('data-index', index);
});
英文:
Try this :
$('.item').each(function(i) {
var index = 3 * Math.floor(i / 3) + 3;
$(this).attr('data-index', index);
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论