代码之家  ›  专栏  ›  技术社区  ›  Mauro74

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

  •  1
  • Mauro74  · 技术社区  · 16 年前

    使用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 回复  |  直到 16 年前
        1
  •  3
  •   Nick Craver    16 年前

    你可以使用 .each() 这样地:

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

    ID不能以数字开头,也不能以HTML4开头,所以我在上面添加了前缀。这个 () 回调函数接收索引和元素作为参数,它基于0,因此添加 1 如果你想开始的话 .

    You can test it out here .

        2
  •  3
  •   Matt user129975    16 年前

    .attr() accepts functions

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