Skip to main content
 首页 » 编程设计

jquery:查找并循环div内具有特定ID的所有跨度

2026年07月28日798°冷暖

我有一个为每个项目编号的列表(1,2,3,4..)。我有一个删除项目的函数,但是当它删除项目时,列表编号不再按顺序排列(1,3,4...)。

我想做的是找到以“id_”开头的所有范围并获取完整的 ID,以便可以将数字重置为正确的顺序。

$('[id^="table_"]').each(function(index, table){ 
 
}); 

我尝试的方式是不知道如何获取跨度的 ID。

<div id="list"> 
 
  <div id="list_1"> 
    <table border="0" width="100%" id="table_1"> 
      <tbody> 
        <tr> 
          <td> 
            <span id="id_1">1</span> 
          </td> 
        </tr> 
      </tbody> 
    </table> 
  </div> 
 
  <div id="list_2"> 
    <table border="0" width="100%" id="table_2"> 
      <tbody> 
        <tr> 
          <td> 
            <span id="id_2">2</span> 
          </td> 
        </tr> 
      </tbody> 
    </table> 
  </div> 
 
</div> 

谢谢

已更新

好吧,我从每篇文章中提取了一些内容来得到这个

var i = 1; 
 
$('span[id^="id_"]', "#list").each(function(index){ 
 
   var id = this.id; 
   $('#'+id).html(i+'. '); 
 
   i++; 
 
}); 

感谢大家的帮助。

请您参考如下方法:

更新我错过了您已经有一个each循环。看起来不错,除了您似乎正在寻找以“table_”开头的 id,但您没有任何(您有“list_”和“id_”)。而且,您的工作完全不受限制,这可能会需要大量工作。选择器越窄越好(通常)。

The way I am trying to do it I cannot figure out how to get the ID of the span.

在 each 循环中,DOM 元素的 id 可用作 this.id。

我原来的答案解决了如何使用您引用的标记来执行此操作。

<小时 />

原始答案:

jQuery 有 "attribute starts with" selector ,因此您可以找到所有 span 且 id 以“id_”开头的子级,然后循环为它们分配新 ID:

$("#list").find('span[id^="id_"]').each(function(index) { 
    this.id = "id_" + (index + 1); 
}); 

使用 find找到它们,然后 each循环遍历它们。我假设您想以 1 而不是 0 开始编号,因此将 1 添加到 jQuery 传递给 each 的 index 中。可以使用原始 DOM 元素(each` 回调中的 this)来分配 ID,因为这并不复杂。

尽管实际上,您不需要单独调用 find,您只需使用后代选择器即可:

$('#list span[id^="id_"]').each(function(index) { 
    this.id = "id_" + (index + 1); 
}); 

Live example

<小时 />

进一步更新:如果您真的想玩得开心,您可以对列表、列表中的表格以及表格中的跨度重新编号:

$('#list div[id^="list_"]').each(function(listIndex) { 
  // This is called for each list, we renumber them... 
  ++listIndex; // So it's 1-based 
  this.id = "list_" + listIndex; 
 
  // ...then process the tables within them 
  $(this).find('table[id^="table_"]').each(function(tblIndex) { 
    // Called for each table in the list, we renumber them... 
    ++tblIndex; // 1-based 
    this.id = "table_" + listIndex + "_" + tblIndex; 
 
    // ...then process the spans 
    $(this).find('span[id^="id_"]').each(function(spanIndex) { 
      // Called for each span in the table 
      ++spanIndex; // 1-based 
      this.id = "id_" + listIndex + "_" + tblIndex + "_" + spanIndex; 
    }); 
  }); 
}); 

Live example