0

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>

リンクをクリックして、そのリンクが含まれている行を削除しても、何も起こりません。スクリプトエラーはありませんので、ロジックである必要があります。

4

1 に答える 1

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(.. と、存在する要素 (なし) にのみ影響し、動的に作成される要素には影響しません。

于 2013-02-27T03:35:25.723 に答える