【问题标题】:Can't delete dynamically added table row无法删除动态添加的表格行
【发布时间】:2013-07-31 13:42:01
【问题描述】:

我对 jquery 很陌生,我想通过以下方式添加和删除表行 点击添加或删除图片。

添加按钮运行良好,手动添加的行和删除按钮运行良好,但如果我添加一个新行,然后单击新行的删除按钮,它什么也不做。

我已经尝试搜索谷歌并测试所有答案,但似乎没有一个适合我。

    <script type="text/javascript">
            $(document).ready(function(){
                    var idCount = 0;
                    idCount++;
                    var new_row="<tr><td><span style='float:left; margin-left:20px;'>IP:&nbsp;</span><input name='ipaddr' type='text' /></td><td><img src='images/delete.png' width='20px' height='20px' id='deleteRow' /></td></tr>";
                    $("table#ipList img#addRow").click(function() {
                            $("table#ipList").append(new_row);
                    });
                    $("table#ipList img#deleteRow").click(function() {
                            //$("img#deleteRow").parents("tr").remove();
                            //$("img#deleteRow").parent().parent().last().remove();
                            $("img#deleteRow").last().parent().parent().remove();
                    });
            });
    </script>
    </head>
    <body>
    <table id="ipList">
            <tr>
                    <td><span style="float:left; margin-left:20px;">IP:&nbsp;</span><input name="ipaddr" type="text" /></td>
                    <td><img src="images/add.png" width="20px" height="20px" id="addRow" /></td>
            </tr>
            <tr>
                    <td><span style="float:left; margin-left:20px;">IP:&nbsp;</span><input name="ipaddr" type="text" /></td>
                    <td><img src="images/delete.png" width="20px" height="20px" id="deleteRow" /></td>
            </tr>
    </table>

【问题讨论】:

  • 你为什么要评论 var new_row?
  • 另外,如果 ID 是唯一的,则不需要 table#ipList img#addRow#addRow 就足够了。

标签: jquery dynamic row add


【解决方案1】:

以这种方式使用委托:

但 ID 在上下文页面上必须是唯一的!

 $(document).ready(function () {
     var idCount = 0;
     idCount++;
     $("#ipList").on('click', "#addRow", function () {
         $("#ipList").append(new_row);
     });
     $("#ipList").on('click', "#deleteRow", function () {
         $("#deleteRow").closest('tr').remove();
     });
  });

【讨论】:

  • 哇,谢谢,这就像一个魅力:) 最后一个问题,我如何将 idCount 附加到新的输入类。
【解决方案2】:

您将需要事件委托。为此使用 on() 方法。 http://api.jquery.com/on/

【讨论】:

    猜你喜欢
    • 2013-02-12
    • 2018-08-23
    • 1970-01-01
    • 2021-06-03
    • 2015-09-26
    • 2017-04-05
    • 1970-01-01
    • 2013-04-05
    • 2016-06-22
    相关资源
    最近更新 更多