使用Jquery连续删除和更新动态创建的表行id

Delete and Update dynamically created Table row ID's serially using Jquery

本文关键字:创建 id 动态 更新 Jquery 连续 删除 使用      更新时间:2023-09-26

例如,我在表上使用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>
<<p> HTML部分/strong>
<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>