无法删除动态添加的表行

时间:2013-07-31 13:42:02

标签: jquery dynamic row add

我对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>

2 个答案:

答案 0 :(得分:4)

以这种方式使用委托:

但在上下文页面上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();
     });
  });

答案 1 :(得分:1)

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

相关问题