我的 View 中有当前代码:
<script>
$(document).ready(function()
{
$("#add_instruction").click(function(){
$("#instructions").append("<tr><td></td><td><input type='text' name='recipe_instruction[]' size='60'/></td></tr>");
});
$("#remove_instruction").click(function(){
var counter = $("#instructions").children("tr").length;
if(counter>1){
$("#instructions tr:last").remove();}
});
});
</script>
</head>
<body>
<table>
<th colspan='2'>Recipe Details</th>
<tr>
<td>Name:</td>
<td><input type='text' name='recipe_name'/></td>
</tr>
<tr>
<td>Description:</td>
<td><textarea cols='50' rows='5'name='recipe_description'></textarea></td>
</tr>
</table>
<table id='instructions'>
<th colspan='2'>Recipe Instructions</th>
<tr>
<td><input type='button' id='add_instruction' value='Add more instruction' /></td>
<td><input type='button' id='remove_instruction' value='remove last instruction'/></td>
</tr>
<tr>
<td></td>
<td><input type='text' name='recipe_instruction[]' size='60'/></td>
</tr>
</table>
添加 tr 可以,但删除不起作用。另外,我做错了吗?在删除中,我认为这是因为我的 if 反驳声明。如果我不添加一个 if 语句来跟踪是否只剩下 1 个 tr,则删除函数将通过删除所有 tr(如果没有)来破坏表。我应该怎么做?
编辑:
<table>
<th colspan='2'>Recipe Details</th>
<tr>
<td>Name:</td>
<td><input type='text' name='recipe_name'/></td>
</tr>
<tr>
<td>Description:</td>
<td><textarea cols='50' rows='5'name='recipe_description'></textarea></td>
</tr>
<tr id='instructions'>
<td><input type='button' id='add_instruction' value=' Add more instruction ' /></br>
<input type='button' id='remove_instruction' value='Remove last instruction'/></td>
<td id='instruction'><input type='text' name='recipe_instruction[]' size='60'/></br></td>
</tr>
</table>
有什么方法可以删除到只剩下1吗?
最佳答案
你需要
$("#remove_instruction").click(function () {
var $trs = $("#instructions tr");
if ($trs.length > 3) {
$trs.last().remove();
}
});
演示:Fiddle
- table.children('tr'),将无法工作,因为浏览器在表格和 trs 之间添加了一个
tbody
- 您有 2 个静态行,您需要 2 + 1
- 最好缓存
tr
结果并在if
条件中使用它
关于javascript - Jquery 删除最后一个 tr 直到剩下 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22475490/