如何使用jquery向元素添加渐进ID?

时间:2010-07-20 23:40:46

标签: jquery addattribute

使用jquery我想为一系列div添加一个id,但当然id需要总是不同的,所以我想有一个渐进的数字,比如id =“1”,id =“2”,id =“3”等。

这是我的标记:

            

                内容             

        
    <div class="box">
        <p>
            content
        </p>
    </div>
    <div class="box">
        <p>
            content
        </p>
    </div>
    <div class="box">
        <p>
            content
        </p>
    </div>

我尝试了一个.each()循环,但我不知道要传递什么作为集合(可能是$('。box')。lenght()?但返回的数字不是集合)以及如何实现回调功能。 有什么帮助吗?

提前致谢:)

莫罗

2 个答案:

答案 0 :(得分:3)

您可以像这样使用.each()

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

ID不能以数字开头,不能以HTML4开头,所以我在上面添加了一个前缀。 .each()回调函数接收索引和元素作为参数,它是从0开始的,因此如果您希望它以1开头,请添加1

You can test it out here

答案 1 :(得分:3)

.attr() accepts functions

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