Javascript 如何使用.remove函数修复给定行以避免删除
我创建了一个可以动态添加和删除的表。我只是在删除一行时遇到了一个小问题。我希望我的第一行被修复,因为当我使用remove时,它会删除我给定的行 表:Javascript 如何使用.remove函数修复给定行以避免删除,javascript,php,jquery,twitter-bootstrap-3,Javascript,Php,Jquery,Twitter Bootstrap 3,我创建了一个可以动态添加和删除的表。我只是在删除一行时遇到了一个小问题。我希望我的第一行被修复,因为当我使用remove时,它会删除我给定的行 表: <div class = "col-md-12"> <table class = "table" id = "customFields"> <thead> <tr> <th>Stock No.</th
<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>
我使用了最后一个函数来删除行,但这只删除了一个文本字段。如何在4之前删除此项?任何帮助都将不胜感激 您应该选择最后一行,而不是最后一个表datatd。我的意思是在$customFields td:last.中删除;语句,而不是使用td:last,请使用tr:last 我在这个tr表示行,td表示行的单个单元格 你应该阅读和探索 要始终保留第一行,请计算tr长度,然后执行删除操作
$("#removeRow").click(function()
{ if($('#customFields tbody tr').length== 1){
// only one row left
alert("Cant delete first row")
}else
{
$('#customFields tr:last').remove();
}
});
既然你的妻子也有个tr。因此,请使用此选项删除
$('#customFields tbody tr:last').remove();
它将仅从车身上删除tr此工作!但是我的第一行被删除了?我如何才能取消删除我的第一行?@Francisunox:点击我答案中的工作演示,它起作用了perfect@Francisunoxx:您想让tr始终取消删除吗?是的,正是因为当我按两次或三次“删除”按钮时,它会删除我要取消删除的第一行,也会删除第一行。我知道您在那里做了什么,您只需设置长度:p您太棒了!此删除是第一行,也是第一行
$('#customFields tbody tr:last').remove();