我正在使用jQuery删除一个名为"CCD_ 1";有多个元素具有此类名。
$(".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>
当我单击no单选按钮时,元素不会被删除,我做错了什么?
您的jQuery删除元素是错误的。在$(this).parent().next(".added").remove();
中,$(this)
是输入元素,因此它的父元素只是.radio-group
元素。您需要将其更改为$(this).parents('.radio-wrapper').next(".added").remove();
即使以上也不起作用,因为.radio-wrapper
和.added
之间有一个<div>
,要使其起作用,您需要使用next()
两次:added
0
我不知道.steps-row-first
元素到底在哪里
但是尝试使用parents返回,然后选择parents的兄弟姐妹来针对您的div添加类,如下所示:
....
if($(this).val() == 'no') {
$(this).parents(".form-group").siblings(".added").remove();
}
....
$(".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((查找所有类。添加并删除它