我将动态行添加到表中,我有一个"删除行"按钮从表中删除当前行。它正常工作,除了我想在表格中至少留下一行。为此,我添加了一个测试来获取表中当前的行数,但它总是返回1,它的值不会更新,为什么不呢?
这是表格:
<table id="fla_inf" width="100%">
<tr>
<th class="tab_header" colspan="6">Flavors and Additives</th>
</tr>
<tr>
<th class="tab_header_nam">Flavor Brand</th>
<th class="tab_header_nam">Flavor Name</th>
<th class="tab_header_nam">Dropper Type</th>
<th class="tab_header_nam">Quantity</th>
<th class="tab_header_nam">Total %</th>
<th class="tab_header_nam">Add/Remove row</th>
</tr>
<tbody>
<tr>
<td><select id="marque.0" name="marque,0"></select></td>
<td><select id="arome.0" name="arome.0"></select></td>
<td><select id="dropper.0" name="dropper.0"></select></td>
<td><input id="quantity.0" name="quantity.0" type="number"/></td>
<td><input id="fla_perc.0" name="fla_perc.0" type="number" min="0" max="100"/></td>
<td><input class="addline" type="image" src="http://spitilab.com/wp-content/uploads/2015/01/add.png"><input class="remline" type="image" src="http://spitilab.com/wp-content/uploads/2015/01/delete.png"></td>
</tr>
</tbody>
</table>
以下是代码的删除部分:
// Remove row from the table
$(document).on('click', '.remline', function() {
alert($('#fla_inf').length);
if ($('#fla_inf').length > 1) {
$(this).closest('tr').remove();
}
});
答案 0 :(得分:2)
你需要找到tr元素的长度:
$('#fla_inf tr').length;
完整代码:
$(document).on('click', '.remline', function() {
alert($('#fla_inf tr').length);
if ($('#fla_inf tr').length > 1) {
$(this).closest('tr').remove();
}});
答案 1 :(得分:0)
如果你想在表体中保留一行,不包括标题中的行(你有2行),你可以使用:
$(document).on('click', '.remline', function() {
alert($('#fla_inf tbody tr').length);
if ($('#fla_inf tbody tr').length > 1) {
$(this).closest('tr').remove();
}
});