2011-07-16 41 views
0

我有以下的html。它的表可以包含许多行id = rows_x。jQuery从类元素中重命名为

<div class="row_table" id="row_1"> 
<div class="row_table" id="row_2"> 
<div class="row_table" id="row_3"> 
<div class="row_table" id="row_4"> 

然后,我有ID按钮,一旦点击会删除ID = “row_2”

$("#button").click(function(){ 
    $('#row_2').remove(); 
    /* Rename rows id goes here */ 
} 

现在我的问题:

由于row_2已被删除,我需要能够重命名所有后续行。

row_3应该成为row_2等..

+0

我可以问你为什么这么做? (这些ID的目的是什么?) – meo

回答

4

我建议:

$("#button").click(function(){ 
    $('#row_2').remove(); 

    // iterates through each of the elements matched by the selector 
    $('.row_table').each(
      // i represents the index of each of the elements 
      function(i){ 
       // sets the id of each of the returned elements 
       // to the string concatenated with the expression 'i + 1' 
       this.id = 'row_' + (i+1); 
      }); 
}); 

JS Fiddle

+0

但第3行和第4行应该成为第2行和第3行 – Yannick

+0

你看过[JS小提琴](http://jsfiddle.net/davidThomas/tA2hm/)吗?他们是这样。除非你想改变行的文本内容? –

+0

更新了[JS小提琴](http://jsfiddle.net/davidThomas/tA2hm/1/),以演示改变的'id'。 –