jQuery添加/删除项目并重置计数器

时间:2016-01-22 02:10:47

标签: javascript jquery

我有以下代码:

var counter = $("#myTable tbody").children().length;

删除功能:

$(document).on('click', 'a.remove', function() {
    if(counter == 1) {
        return false;
    }

    $(this).closest('tr').fadeOut().remove();
    counter--;
});

添加功能:

$('#add').on('click', function() {
  if (counter > 10) {
      return false;
  }
  counter++;
  var newTr = $('<tr data-id="' + counter + '"></tr>');

  newTr.html(
      '<td><i class="icon reorder"></i></td>\
      <td><small>' + counter + '.</span></td>\
      <td> <input type = "text" name = "price[]" data-id = "' + counter + '"></td>\
      <td><a class="remove"><i class="icon delete"></i></a></td>\
      ');
  });

在点击时删除项目时,我想重置计数器,因此从{1}开始按顺序恢复<small></small>之间的值。

1 个答案:

答案 0 :(得分:0)

在删除项目后,您似乎需要循环浏览所有tr并使用新值再次设置small textinput data-id

$(document).on('click', 'a.remove', function() {
    if(counter == 1) {
        return false;
    }

    $(this).closest('tr').fadeOut().remove();

    counter = 0;

    $("#myTable tbody").children().each(function(){
        counter++;
        $(this)
            .find("small").text( counter )
            .end()
            .find("input").attr( "data-id", counter );
    });
});
相关问题