2016-01-22 68 views
0

我有下面的代碼: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>\ 
     '); 
    }); 

當移除項目點擊,我想重置計數器,所以<small></small>之間的值從1開始依次恢復。

+0

刪除通過所有tr和設置small textinput data-id項目,環能介紹_「在從1開始序列復原」 _?預期的結果是什麼? – guest271314

+0

試着把你的代碼放在jsfiddle上,讓我們知道什麼是預期的結果,所以我們可以幫助你 – kdureidy

回答

0

好像你需要,之後再次用新值

$(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); 
    }); 
}); 
+0

非常感謝,它的作品完美。 – Alko

+0

不客氣! – Leonardo