使用 jquery 为每个元素增加属性值 (int)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6996718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Increment attribute value (int) for each element using jquery
提问by maze
i have an unknown number of section elements:
我有未知数量的部分元素:
<section id="foo">
...
</section>
<section id="bar">
...
</section>
For each section which is present I need to add an attribute "data-serial" which is an integer starting at 0 and being incremented by 1 for each section present, for example the above would turn into:
对于存在的每个部分,我需要添加一个属性“data-serial”,它是一个从 0 开始的整数,并为每个存在的部分增加 1,例如上面的将变成:
<section id="foo" data-serial="0">
...
</section>
<section id="bar" data-serial="1">
...
</section>
<section id="bla" data-serial="2">
...
</section>
...
How can I achieve this using jQuery?
如何使用 jQuery 实现这一目标?
Thanks
谢谢
回答by James Allardice
var current = 0;
$("section").each(function() {
$(this).data("serial", current);
current++;
});
This loops through all section
elements in the document, and attaches the value of current
to each element using the jQuery data
method.
这会遍历section
文档中的所有元素,并current
使用 jQuerydata
方法将 的值附加到每个元素。
回答by Chris
A modified version of James Allardice's answer taking advantage of the rarely used parameters that each passes to the function it is given. The first parameter is the index of the current iteration of the loop.
James Allardice 的答案的修改版本利用了每个传递给它的函数的很少使用的参数。第一个参数是当前循环迭代的索引。
$("section").each(function(index) {
$(this).attr("data-serial", index);
});
回答by Tim Rogers
$("section").each(function(i, e) { $(e).attr("data-serial", i) });
回答by MikeM
something like
就像是
var i = 0;
$('section').each(function() {
$(this).data('serial', i++);
});