jQuery rename id from class elements
I have the following html. Its a table that can contains many rows id=rows_x.
<div class="row_table" id="row_开发者_如何学C1">
<div class="row_table" id="row_2">
<div class="row_table" id="row_3">
<div class="row_table" id="row_4">
Then I have id button that once clicked will delete the id ="row_2"
$("#button").click(function(){
$('#row_2').remove();
/* Rename rows id goes here */
}
And now for my question:
Since row_2 has been removed I need to be able to rename all following rows.
row_3 should become row_2, etc...
I'd suggest:
$("#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.
精彩评论