gpt4 book ai didi

javascript - 删除动态表单元素 jQuery

转载 作者:行者123 更新时间:2023-11-28 16:36:32 25 4
gpt4 key购买 nike

我目前正在使用 jQuery 向我的网页添加动态表单元素。添加每个表单元素后,我希望用户能够在必要时删除该元素。我目前正在尝试使用 jQuery 执行此操作,我正在尝试定位某些类并将其删除,但是目前什么也没有发生,我的控制台中也没有任何错误。

这是我的删除代码,这是我制作的 JS fiddle。

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

https://jsfiddle.net/zp9faa2h/

最佳答案

.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

关于javascript - 删除动态表单元素 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34437918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com