动态ID不适用于克隆

时间:2017-05-22 13:39:09

标签: jquery html

我有一个克隆行选项的表。当我为一个标签克隆一行时,输入id为text_0,而不是改变它以前的输入id。 我希望标记输入ID应该像text_1text_2,' text_3一样递增...等等,当我们克隆一行时。 以下是Html:

<table class="" id="table-data">
  <thead>
    <tr>
      <th> Qty</th>
      <th>days</th>
      <th>rate</th>
      <th>rowtotal</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <input type="text" autocomplete="off" name="qty[]" placeholder="Qty" class="form-control Qty">
      </td>
      <td>
        <input type="text" autocomplete="off" name="days[]" placeholder="Days" class="form-control Days">
      </td>
      <td>
        <input type="text" autocomplete="off" name="rate[]" placeholder="Rate" class="form-control rate">
      </td>

      <td>
        <input type="text" autocomplete="off" readonly="" name="row_total[]" id="row_total0" placeholder="Row    Total" class="form-control rowTotal">
        <a class="Comment" data-toggle="modal"  data-target="#commentModal"><input type="" id="text_0"></a>
      </td>
      <td>
        <div class="btn-group btn-group-sm" role="group" aria-label="">
          <button type="button" class="addline btn btn-sm btn-primary">+</button>
          <button type="button" class="delete btn btn-sm btn-danger">-</button>
        </div>
      </td>
    </tr>
  </tbody>
</table>

Jquery:

$(document).on('click', '.addline', function () {
  var $tr = $(this).closest('tr');
  var $lastTr = $tr.closest('table').find('tr:last');
  var $clone = $lastTr.clone();
  $clone.find('td').each(function () {
    var el = $(this).find(':first-child');
    var id = el.attr('id') || null;
    if (id) {
      var i = id.substr(id.length - 1);
      var prefix = id.substr(0, (id.length - 1));
      el.attr('id', prefix + (+i + 1));
    }
  });

  $clone.find('input:text').val('');
  $tr.closest('tbody').append($clone);

});
$(document).on('click', '.delete', function () {
  //dont delete the last data row
  var parentId = $(this).closest('table').attr('id');

  if ($('#' + parentId + '  tr').length > 2) {
    var $tr = $(this).closest('tr');
    $tr.remove();
  }
  return false;
});

如何更改标签输入的ID。有什么建议吗?

js fiddle demo here

1 个答案:

答案 0 :(得分:1)

代码/行为有点令人困惑,但似乎el是长度为2的集合,与您要修改的id的两个父元素相匹配。但由于您没有循环el,因此只设置了一个id。在经典的jQuery风格中,它默默地发生在匹配集上的所有内容中:

el.attr('id', prefix + (+i + 1));

相反,循环遍历el并单独设置每个。像这样:

var el = $(this).find(':first-child');
$(el).each(function () {  // loop over the matched set here
  var id = $(this).attr('id') || null;  // target the item in the loop
  if (id) {
    debugger;
    var i = id.substr(id.length - 1);
    var prefix = id.substr(0, (id.length - 1));
    $(this).attr('id', prefix + (+i + 1));  // target the item in the loop
  }
});

Updated jsFiddle