我使用jQuery删除一个名为"added“类的元素,这个类名有多个元素。
$(".steps-row-first").on("change", ".anotherCheese", function() {
if($(this).val() == 'no') {
$(this).parent().next(".added").remove();
}
else
{
$(".steps-row-first").append("<div class='added'></div>");
}
});下面是HTML:
<div class="steps-row-first">
<div class="form-group">
<div class="radio-wrapper">
<div class="radio-group">
<input type="radio" class="anotherCheese" name="anotherCheese" value="yes">
<label>Yes</label>
</div>
<div class="radio-group">
<input type="radio" class="anotherCheese" name="anotherCheese" value="no">
<label>No</label>
</div>
</div>
</div>
<div style="clear:both;"></div>
<div class="added"></div>
</div>当我单击“不”单选按钮时,元素不会被移除,我做错了什么?
发布于 2022-03-11 20:17:14
您的jQuery删除元素是错误的。在$(this).parent().next(".added").remove();中,$(this)是输入元素,因此它的父元素只是.radio-group元素。您需要将其更改为$(this).parents('.radio-wrapper').next(".added").remove();
即使在上面也不能工作,因为在.radio-wrapper和.added之间有一个.added,要使它工作,您需要使用next()两次:$(this).parents('.radio-wrapper').next().next(".added").remove();
发布于 2022-03-11 20:22:53
我不知道,.steps-row-first元素到底在哪里?
但是,尝试使用父母回来,然后选择父母的兄弟姐妹通过添加类来针对您的div,如下所示:
....
if($(this).val() == 'no') {
$(this).parents(".form-group").siblings(".added").remove();
}
....发布于 2022-03-14 07:29:23
$(".steps-row-first").on("change", ".anotherCheese", function() {
if($(this).val() == 'no') {
$(".steps-row-first").find(".added").remove();
}
else
{
$(".steps-row-first").append("<div class='added'></div>");
}
});
可以使用find()查找所有类.added并删除它
https://stackoverflow.com/questions/71444160
复制相似问题