删除行后转换表中的索引引用

时间:2017-02-07 15:39:48

标签: jquery

我们有一个表格,其元素在每个Label / Input和TR ID上都有索引,还有一个Remove按钮。单击“删除”时,该行将被删除,并且下面的所有引用都必须向上移动1(-1)。

我们可以尝试找出手动换档,但有更简单的方法吗?

受影响的索引 - 包括项目:TR,每个标签ID,每个输入ID,每个输入名称

HTML:

<tr id="period0">
   <td>
      <label for="budgetPeriod0">Enter the Budget Period number.</label>
      <input id="budgetPeriod0" name="name_period_0" />
   </td>
   <td>
      <label for="amount0">Enter the amount.</label>
      <input id="amount0" name="name_amount_0">
   </td>
</tr>

jQuery删除TR(已实现)Shift(未实现):

   removeRecord : function(index) {
          var v= "tr:eq("+index+")";
          $("#incomeTable >tbody").find(v).remove();

          var id = "#period"+index; 
          $(id).nextAll().each(function(i){
                 //shifting logic goes here

          });

1 个答案:

答案 0 :(得分:1)

我不确定你是怎么调用删除的。我只想重新索引整个表格,删除一行...

将索引内置到您的ID /名称中会让我感到奇怪。

&#13;
&#13;
$(function() {
  reindex();
});

function removeRecord(index) {
  var v = "tr:eq(" + index + ")";
  $("#incomeTable >tbody").find(v).remove();

  reindex();

}

function reindex() {
  var $row;
  $.each($("#incomeTable>tbody>tr"), function(idx, elem) {
    $row = $(elem);
    $row.attr("id", $row.attr("id").replace(/\d+/, idx));
    $.each($row.find("[for]"), function(i, label) {
      $(label).attr("for", $(label).attr("for").replace(/\d+/, idx));
    });
    $.each($row.find("[id]"), function(i, input) {
      $(input).attr("id", $(input).attr("id").replace(/\d+/, idx));
    });
    $.each($row.find("[name]"), function(i, input) {
      $(input).attr("name", $(input).attr("name").replace(/\d+/, idx));
    });
  });
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="incomeTable">
  <tbody>
    <tr id="period0">
      <td>
        <label for="budgetPeriod0">Enter the Budget Period number.</label>
        <input id="budgetPeriod0" name="name_period_0" />
      </td>
      <td>
        <label for="amount0">Enter the amount.</label>
        <input id="amount0" name="name_amount_0">
      </td>
    </tr>
    <tr id="period0">
      <td>
        <label for="budgetPeriod0">Enter the Budget Period number.</label>
        <input id="budgetPeriod0" name="name_period_0" />
      </td>
      <td>
        <label for="amount0">Enter the amount.</label>
        <input id="amount0" name="name_amount_0">
      </td>
    </tr>
    <tr id="period0">
      <td>
        <label for="budgetPeriod0">Enter the Budget Period number.</label>
        <input id="budgetPeriod0" name="name_period_0" />
      </td>
      <td>
        <label for="amount0">Enter the amount.</label>
        <input id="amount0" name="name_amount_0">
      </td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;