$(document).on('click', '#add', function () {
var newItemHTML = "<tr class='additionalcomplainant'><td><center><input type='text' name='' id='' /><br> <small><i>First Name</i></small></center></td><td><center><input type='text' name='' id='' /><br> <small><i>Middle Name</i></small></center></td><td><center><input type='text' name='' id='' /><br> <small><i>Last Name</i></small> </center></td></tr><tr class='additionalcomplainant'><td><center><input type='text' name='' id='' /><br> <small><i>City/Province</i></small></center></td><td><center><input type='text' name='' id=''/><br> <small><i>Town/Municipality</i></small></center></td><td><center><input type='text' name='' id='caseinfocomplaintlname' /><br> <small><i>Barangay/District</i></small></center></td> </tr><tr class='additionalcomplainant'><td><center><input type='text' name= id='' /><br> <small><i>Contact Number</i></small></center></td></tr>";
$("table#t1table tr").last().before(newItemHTML);
});
$(document).on('click', '#remove', function () {
});
这就是我使用 jquery 在我的表中添加行的方式。我将如何在另一个按钮单击时删除同一组行。我想删除这些行,例如,如果用户误点击了按钮并且行数超过需要
最佳答案
您可以保留对添加行的引用:
var addedRows = [];
$(document).on('click', '#add', function() {
var $row = $("<tr class='additionalcomplainant'><td><center><input type='text' name='' id='' /><br> <small><i>First Name</i></small></center></td><td><center><input type='text' name='' id='' /><br> <small><i>Middle Name</i></small></center></td><td><center><input type='text' name='' id='' /><br> <small><i>Last Name</i></small> </center></td></tr><tr class='additionalcomplainant'><td><center><input type='text' name='' id='' /><br> <small><i>City/Province</i></small></center></td><td><center><input type='text' name='' id=''/><br> <small><i>Town/Municipality</i></small></center></td><td><center><input type='text' name='' id='caseinfocomplaintlname' /><br> <small><i>Barangay/District</i></small></center></td> </tr><tr class='additionalcomplainant'><td><center><input type='text' name= id='' /><br> <small><i>Contact Number</i></small></center></td></tr>");
addedRows.push($row);
$("#t1table tr").last().before($row);
});
$(document).on('click', '#remove', function() {
var $row = addedRows.pop();
if ($row) $row.remove();
});
在上面的代码中,我保留了一个数组。添加的行在添加时被推到末尾,并在删除时从末尾被删除(使用pop
)。一个优点是,如果您决定在表格中的随机位置添加,它仍然有效。
或者,假设除了您添加的行之外没有任何其他 .additionalcomplainant
行,您可以这样做
$(document).on('click', '#remove', function() {
$('#t1table .additionalcomplainant').last().remove();
});
顺便说一句,不要使用 "table#t1table"
作为选择器:"#t1table"
是相同的,而且速度更快。
关于javascript - 删除添加的行集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30665613/