如何使用jQuery删除动态生成的Div

时间:2016-01-15 09:03:04

标签: javascript jquery html

我想使用jquery删除动态生成的div,删除按钮将与每个div一起使用。因此,当我单击任何删除按钮时,它将从DOM中删除该div。

<div class="form-group" id="drag">    
    <div class="col-md-2">
        <input type="text" class="form-control" id="name1" placeholder="Name">    
    </div>
    <div class="col-md-2">
        <input type="text" class="form-control" id="eng1" placeholder="Description Eng">    
    </div>
    <div class="col-md-2">
        <input type="text" class="form-control" id="ar1" placeholder="Description Ar">    
    </div>           
    <div class="col-md-2">
        <a id="remove" href="javascript:;" class="btn btn-sm red"> 
            Remove
            <i class="fa fa-close"></i>                                                                        
        </a>
    </div>
</div>

3 个答案:

答案 0 :(得分:2)

如果您要在div div内生成button,则可以添加以下函数,让button让父div消失:

function removeParent()
{
    //remove button click, remove the parent div from the dom
    $(this).parent().parent().remove();
    //in your specific case you want the parent parent div to be removed since the button is encapsulated by 2 divs.
}

然后,您需要将此功能添加到按钮的onclick侦听器。只需在html onclick='removeParent()'中设置或使用javascript:

即可
//gerenate div + button
mybutton.addEventListener('click', removeParent, false);

答案 1 :(得分:1)

尝试如下。使用Array class代替remove,因为id应该是唯一的。

&#13;
&#13;
id
&#13;
$('body').on('click', '.remove', function(){
    $(this).closest('.form-group').remove();
});
&#13;
&#13;
&#13;

答案 2 :(得分:1)

$('body').on('click', '#remove', function(){
   $(this).closest('.form-group').remove();
});

但是拥有多个具有相同ID的元素是不正确的。建议您将ID更改为类

相关问题