2015-12-23 197 views
1

我目前使用jQuery将动态表单元素添加到我的网页。在添加每个表单元素后,我希望用户能够根据需要删除该元素。我目前尝试使用jQuery来做到这一点,我试图定位某些类并将其删除,但此刻没有任何事情发生,并且我的控制台中没有任何错误。删除动态表单元素jQuery

这是我的删除代码,这里是我做的JS小提琴。

$(document).on('click', '.ingredient .remove', function() { 
    $(this).parents('.ingredient .quantities').remove(); 
    return false; 
}); 

https://jsfiddle.net/zp9faa2h/

回答

1

.ingredient.quantities有不同的父母。这就是为什么.parents('.ingredient .quantities')返回什么都不能删除。

这将是最好能包住这两个在父DIV,但你可以做这样的: -

$(document).on('click', '.ingredient .remove', function() { 
    $(this).closest('.ingredient').parent().next().remove(); 
    $(this).closest('.ingredient').parent().remove(); 
    return false; 
}); 

这则查找最接近.ingredient上升到父,并删除下一个容器.quantities。然后删除.ingredients的父项。

Fiddle