简体   繁体   English

删除动态表单元素jQuery

[英]Removing dynamic form elements jQuery

I am currently using jQuery to add dynamic form elements to my webpage. 我目前正在使用jQuery向我的网页添加动态表单元素。 After each form element is added I want the user to be able to remove that element if necessary. 在添加每个表单元素之后,我希望用户能够在必要时删除该元素。 I currently try and do this using jQuery, I am attempting to target certain classes and remove them, however at the moment nothing is happening and there aren't any errors in my console. 我目前正在尝试使用jQuery进行此操作,我正在尝试定位某些类并将其删除,但是目前没有任何反应,并且控制台中没有任何错误。

Here is my remove code and here is a JS fiddle I have made. 这是我的删除代码,这是我制作的JS小提琴。

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

https://jsfiddle.net/zp9faa2h/ https://jsfiddle.net/zp9faa2h/

The .ingredient and .quantities have different parents. .ingredient.quantities具有不同的父代。 Thats why .parents('.ingredient .quantities') returns nothing to remove. 这就是为什么.parents('.ingredient .quantities')返回任何要删除的内容的原因。

it would be best to wrap both these in a parent div, but you could do it like the following:- 最好将它们都包装在父div中,但是您可以像下面这样操作:

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

This then finds the closest .ingredient goes up to the parent and removes the next container .quantities . 然后,这将找到最接近的.ingredient上级到父级,并删除下一个容器.quantities then removes the parent of .ingredients . 然后删除.ingredients的父.ingredients

Fiddle 小提琴

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

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