繁体   English   中英

使用JavaScript删除动态添加的字段

[英]Remove Dynamically Added Fields with Javascript

我有一个表单,其中将初始输入字段克隆为模板,以允许用户添加所需数量的选项。 添加新字段可以正常工作,但是尝试删除它们时,第一个字段可以按预期工作,但是无法删除所有生成的字段。

我对JS的知识很差,但是我认为将其设置为删除父项应该是正确的操作。

<script type="text/javascript">
$(function()
{
    var template = $('#inventoryItems .inventory:first').clone(),
        inventoryCount = 1;

    var addInventory = function()
    {
        inventoryCount++;
        var inventory = template.clone().find(':input').each(function()
        {
            var newId = this.id.substring(0, this.id.length-1) + inventoryCount;
            $(this).prev().attr('for', newId); // update label for (assume prev sib is label)
            this.name = this.id = newId; // update id and name (assume the same)
        }).end() // back to .attendee
        .attr('id', 'inv' + inventoryCount) // update attendee id
        .appendTo('#inventoryItems > fieldset'); // add to fieldset
    };

    $('.btnAddInventory').click(addInventory); // attach event
});

$(function()
{
    var removeInventory = function()
    {
        $(this).parent().remove();
    };

    $('.btnRemoveInventory').click(removeInventory); // attach event
});
</script>

HTML:

                <div id="inventoryItems" class="inventoryItems" style="margin:0; padding:0;">

                    <fieldset style="width:62%; float:left; margin-left: 19%;">

                        <label>Inventory</label>
                        <div id="inv1" class="inventory">
                            <select name="invItem1" style="width:92%;">
                                <?php
                                    $invItem_values = array("id", "name");
                                    display_options_list($dp_conn, $invItem_values, "inventory", "id");
                                ?>
                            </select>

                            <input class="btnRemoveInventory" type="button" style="background: url(images/icn_trash.png) no-repeat; cursor:pointer; border: none;">
                        </div>

                    </fieldset><div class="clear"></div>

                    <!-- Add Inventory Button -->
                    <div style="width:62%; margin:0; padding:0; float: right; margin-right: 19%">
                        <input class="btnAddInventory" type="button" value="Add Item" style="float: right;">
                    </div><div class="clear"></div>

                </div>

通过click() (或任何其他快捷方式事件处理程序)附加事件仅适用于页面加载时可用的元素。 相反,由于要动态附加元素,因此需要使用委托的事件处理程序。 更改此:

$('.btnRemoveInventory').click(removeInventory)

对此:

$('#inventoryItems').on('click', '.btnRemoveInventory', removeInventory)

#inventoryItems事件附加到最近的静态元素#inventoryItems ,然后过滤引发的事件以查看目标是否与.btnRemoveInventory匹配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM