使用 jquery 克隆元素产生不需要的多个副本

Cloning element with jquery producing undesirable multiple copies

本文关键字:不需要 副本 jquery 元素 使用      更新时间:2023-09-26

在我当前的项目中,我有这个jquery函数:

$(document).on("click", "button.multiple", function(){
    $(this).parent().first().find("input.multiple").after( $(this).parent().first().find("input.multiple").clone() );
});

每次单击按钮时,都应该向页面添加新的输入元素,如下所示:

<div>
    <label>Fotos</label>
    <input type="file" class="form-control multiple" name="fotos" />
    <button type="button" class="btn btn-default multiple">
        <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>novo
    </button>
</div>

但是当我单击按钮时,会产生此元素的多个副本。谁能说出这里出了什么问题?

按照上面的评论,我用这段代码解决了这个问题:

$(document).on("click", "button.multiple", function(){
    $(this).parent().first().find("input.multiple").first().after(
        $(this).parent().first().find("input.multiple").first().clone()
    );
});