jQuery动态id rearange

时间:2017-03-02 12:19:41

标签: jquery

我正在尝试为表行获取一个直接的id。

例如,如果您有一个包含5行的表,则行ID应为1 - 5。

但是因为我有一个动态表,可以添加或删除行,当用户在中间某处删除一行时会出现问题。

我们假设您在表格中添加3个新行

row-1
row-2
row-3

如果您删除第二行,则最终会以

结束
row-1
row-3

如果你添加一个新行(因为我从前一行获得了id),你将得到这个

row-1
row-3
row-4

如何解决这个问题?如何动态重新排列行ID?

我认为这必须与行删除绑定,因为如果在中间没有删除行,则添加不是问题。

以下是FIDDLE的示例。检查Web浏览器中的id属性

2 个答案:

答案 0 :(得分:2)

您需要编写代码以重新排列索引1中的行ID。您可以使用gt选择器和.attr()回调函数来定位索引1中的行以设置新ID:

$('#t1 tr:gt(0)').attr('id',function(i,o){
    return "r"+ i++ ;
});

<强> Working Demo

答案 1 :(得分:1)

您可以使用以下内容:

var rows = $('#t1 tr') // get the amount of rows

$.each(rows, function(i, e) {
    $(e).attr("id", "r" + i);// set the new id
})

&#13;
&#13;
$(document).on('click', '#addRow', function() {
  var row = parseInt($('#t1 tr:last-child').attr('id').replace(/[^\d]/g, ''), 10) + 1;
  $('#t1').append('<tr id="r' + row + '"><td><input name="item[]" type="text"/></td><td><input name="quantity[]" type="number"/></td><td><button class="deleteRow">X</button></td></tr>');

  var rows = $('#t1 tr')

  $.each(rows, function(i, e) {
    $(e).attr("id", "r" + i);
  })
});

$(document).on('click', '.deleteRow', function() {
  var row = parseInt($(this).closest('tr').attr('id').replace(/[^\d]/g, ''), 10);

  if (row > 1) {
    $('#r' + row).remove();
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="t1">
  <tr>
    <th>Item</th>
    <th>Quantity</th>
  </tr>
  <tr id="r1">
    <td>
      <input name="item[]" type="text" />
    </td>
    <td>
      <input name="quantity[]" type="number" />
    </td>
    <td>
      <button class="deleteRow">X</button>
    </td>
  </tr>
</table>
<button id="addRow">Add Row</button>
&#13;
&#13;
&#13;

相关问题