maz*_*aze 2 int jquery increment
我有一个未知数量的节元素:
<section id="foo">
...
</section>
<section id="bar">
...
</section>
Run Code Online (Sandbox Code Playgroud)
对于每个存在的部分,我需要添加一个属性"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>
...
Run Code Online (Sandbox Code Playgroud)
我怎样才能使用jQuery实现这一目标?
谢谢
Jam*_*ice 13
var current = 0;
$("section").each(function() {
$(this).data("serial", current);
current++;
});
Run Code Online (Sandbox Code Playgroud)
这循环遍历section文档中的所有元素,并current使用jQuery data方法将值附加到每个元素.
Chr*_*ris 12
James Allardice的答案的修改版本利用了很少使用的参数,每个参数都传递给它给出的函数.第一个参数是循环的当前迭代的索引.
$("section").each(function(index) {
$(this).attr("data-serial", index);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25534 次 |
| 最近记录: |