javascript - Jquery 删除最后一个 tr 直到剩下 1

标签 javascript jquery html

我的 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/

相关文章:

javascript - 如何在 Javascript 函数中返回 null

javascript - 无法找出 key 和 Prop 的问题

javascript - 使用onclick函数获取被点击的元素jquery

javascript - 是否允许在链接中执行内联 javascript?

javascript - 拉斐尔JS : arrow's end and start have different color than the path itself

javascript - Chromecast 接收器应用程序 - 意外命令,播放器处于 IDLE 状态

javascript - iOS 12 中的 PWA 在重新打开应用程序时不再重新执行 Javascript

javascript - jQuery:如何获取所有先前元素的宽度总和并将其放入数据属性

javascript - 使列隐藏在handsontable中

javascript - jQuery 仅适用于 Firefox,不适用于 Chrome 或 IE