【问题标题】:Dynamically Add and Remove Table Rows动态添加和删除表格行
【发布时间】:2013-02-12 18:17:59
【问题描述】:

我同时使用 jQuery 添加和删除表行。我可以轻松添加行,但在删除已创建的行时遇到问题。

您可以在此处查看正在运行的页面:http://freshbaby.com/v20/wic/request_quote.cfm,相关代码粘贴在下面。

HTML

<table style="width:600px;" id="product-list" summary="Lists details about products users wish to purchase">
    <thead valign="top" align="left">
        <tr>
            <th>Products</th>
            <th>Language</th>
            <th>Quantity</th>
            <th></th>
        </tr>
    </thead>
    <tbody valign="top" align="left">
        <tr>
            <td>
                <cfselect query="getProductListing" name="product" size="1" display="name" value="name" queryPosition="below">
                    <option value=""></option>
                </cfselect>
            </td>
            <td>
                <select name="language" size="1">
                    <option value="English">English</option>
                    <option value="Spanish">Spanish</option>
                </select>
            </td>
            <td>
                <cfinput name="quantity" required="yes" message="Enter your desired quantity" size="10" maxlength="3" mask="999">
            </td>
            <td valign="bottom"><a href="javascript://" class="addrow">Add Another Product</a></td>
        </tr>
    </tbody>
</table>

JavaScript:

<script>
        $(function() {
            var i = 1;
            $(".addrow").click(function() {
                $("table#product-list tbody > tr:first").clone().find("input").each(function() {
                    $(this).attr({
                      'id': function(_, id) { return id + i },
                      'value': ''               
                    });
                }).end().find("a.addrow").removeClass('addrow').addClass('removerow').text('< Remove This Product')
                .end().appendTo("table#product-list tbody");
                i++;
                return false;
            });

            $("a.removerow").click(function() {
                    //This should traverse up to the parent TR
                $(this).parent().parent().remove();
                return false;
            });
        });
    </script>

当我单击链接以删除包含该链接的行时,没有任何反应。没有脚本错误,所以它必须是逻辑。

【问题讨论】:

  • 尝试改用$(this).closest('tr').remove();。如果这不起作用,请尝试使用 e.preventDefault(); 而不是 return false;,但将其放在函数的顶部。
  • 它没有;在下面的答案中查看原因。

标签: javascript jquery html-table dom-traversal jquery-traversing


【解决方案1】:

试试这个

$("#product-list").on('click','a.removerow',function(e) {
    e.preventDefault();
    //This should traverse up to the parent TR
    $(this).closest('tr').remove();
    return false;
});

这将确保可以删除新创建的元素。当您使用$("a.removerow").click(.. 时,它只会影响存在的元素(无),而不影响将动态创建的元素。

【讨论】:

  • 很好的答案,而且我学到了一些关于不存在的元素交互的新知识。太棒了!
猜你喜欢
  • 2018-08-23
  • 2021-06-03
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-26
相关资源
最近更新 更多