开发者

How to add a progressive IDs to elements with jquery?

Using jquery I want to add an id to a series of divs, but of course the ids need to be always different, so I thought to have a progressive number like id="1", id="2", id="3" etc.

here's my markup:

content

    <div class="box">
        <p>
            content
        </p>
    </div>
    <div class="box">
        <p>
            content
        </p>
    </div>
    <div c开发者_运维技巧lass="box">
        <p>
            content
        </p>
    </div>

I tried an .each() loop but I don't know what to pass as collection (maybe $('.box').lenght()? but returns a number not a collection) and how to implement the callback function. any help please?

Thanks in advance :)

Mauro


You can use .each() like this:

$(".box").each(function(i, div) {
  div.id = "div" + (i+1); //i starts at 0
});

IDs can't start with a number, not in HTML4 anyway, so I've added a prefix above. The .each() callback function receives the the index and the element as arguments, it's 0-based so add 1 if you want it to start with 1.

You can test it out here.


.attr() accepts functions

$(".box").attr('id', function(i) {
    return 'div_' + i;
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜