【问题标题】:How to add a progressive IDs to elements with jquery?如何使用 jquery 向元素添加渐进式 ID?
【发布时间】:2010-07-20 23:40:45
【问题描述】:

使用 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()?但返回一个数字而不是集合)以及如何实现回调功能。 请问有什么帮助吗?

提前致谢:)

毛罗

【问题讨论】:

  • 值得注意的是,为了清楚起见,HTML ID 不能以数字开头

标签: jquery addattribute


【解决方案1】:

你可以像这样使用.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.

【讨论】:

    【解决方案2】:

    .attr() accepts functions

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

    【讨论】:

      猜你喜欢
      • 2019-03-10
      • 1970-01-01
      • 2012-09-26
      • 1970-01-01
      • 2015-10-11
      • 1970-01-01
      • 1970-01-01
      • 2012-07-11
      • 1970-01-01
      相关资源
      最近更新 更多