我创建了一个表,其中 in 可以动态添加和删除。我只是在删除一行时遇到了一个小问题。我希望修复我的第一行,因为当我使用remove()
时它会删除我给出的行。
桌子:
<div class = "col-md-12">
<table class = "table" id = "customFields">
<thead>
<tr>
<th>Stock No.</th>
<th>Unit</th>
<th>Description</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
</tr>
</tbody>
</table>
<button type = "submit" class = "btn btn-primary" id = "addMore">+ Add</button>
<button type = "submit" class = "btn btn-danger" id = "removeRow">- Remove</button>
</div>
脚本:
<script>
$(document).ready(function ()
{
$("#addMore").click(function ()
{
$("#customFields").append('<tr><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td></tr>');
});
$("#removeRow").click(function()
{
$('#customFields td:last').remove();
});
});
</script>
我使用last
函数删除该行,但这只删除了一个文本字段。如何将其删除 4?任何帮助将不胜感激!!
tr
表示行,td
表示行的单个单元格。
您应该阅读并探索有关 HTML 表格的信息
$('#customFields tr:last').remove();
工作演示
并始终保持第一行,计算tr长度,并进行删除操作
$("#removeRow").click(function()
{ if($('#customFields tbody tr').length== 1){
// only one row left
alert("Cant delete first row")
}else
{
$('#customFields tr:last').remove();
}
});
而且由于您的thead
也有tr
.因此,使用此选择删除
$('#customFields tbody tr:last').remove();
它只会从tbody
中删除tr
您应该选择最后一行,而不是最后一个表数据(TD)。我的意思是$('#customFields td:last').remove();
语句中,不要使用 td:last ,请使用 tr:last。
我把它固定在这个小提琴上