开发者

Increment attribute value (int) for each element using jquery

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 i开发者_StackOverflowncremented by 1 for each section present, for example the above would turn into:

<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?

Thanks


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.


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.

http://api.jquery.com/each/

$("section").each(function(index) {
   $(this).attr("data-serial", index);
});


something like

var i = 0;
$('section').each(function() {
    $(this).data('serial', i++);
});


$("section").each(function(i, e) { $(e).attr("data-serial", i) });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜