[英]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.