[英]Delete and Update dynamically created Table row ID's serially using Jquery
例如,我要在表上使用ajax,jquery列出要出售的产品。 每个表格行都获得动态ID的地方,如row_1,row_2,row_3等。
可以选择删除任何行,例如,删除第二行(row_2)。
所以我想要的是,在删除行之后,表的行ID也应该得到更新,可能有一个函数可以执行此操作,例如,我不希望它是row_1,row_3,而是希望它是row_1,row_2 。
我已经在项目中的某个地方随身带了这段代码,只是根据您的需要进行了一些微调。
jQuery部分
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".remove_tr").click(function(){
var tr_id = $(this).parent().attr("id");
var flag = "N"; var row_cnt = 0;
$("#dummy_table tr").each(function(){
if( flag == "Y" ){
$(this).attr("id", "row_"+ row_cnt);
$(this).children("td:first-child").html("row_"+ row_cnt);
$(this).attr("id", "row_"+ row_cnt);
row_cnt++;
}
if( flag =="N" && $(this).attr("id") == tr_id){
var rowArr = $(this).attr("id").split("_");
row_cnt = rowArr[1];
$(this).remove(); flag= "Y";
}
})
});
});
</script>
HTML部分
<table id="dummy_table">
<?php for($i = 0; $i < 10; $i++){ ?>
<tr id="row_<?php echo $i; ?>">
<td>row_<?php echo $i; ?></td>
<td class="remove_tr">remove</td>
</tr>
<?php } ?>
</table>
请让我知道这对你有没有用
这很简单。 运行下面的代码段。
$(".remove").click(function() { $(this).parent().remove(); var counter = 1; $("#foo tr").each(function() { $(this).attr('id', 'row_'+counter); $(this).find('td:first-child').html('row_'+counter); //just to show the result counter++; }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table id="foo"> <tr id="row_1" class="block" > <td>row_1</td> <td class="remove">remove</td> </tr> <br> <tr id="row_2" class="block" > <td>row_2</td> <td class="remove">remove</td> </tr> <br> <tr id="row_3" class="block" > <td>row_3</td> <td class="remove">remove</td> </tr> <br> <tr id="row_4" class="block" > <td>row_4</td> <td class="remove">remove</td> </tr> <br> </table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.