简体   繁体   English

jQuery 使用 next() 和 remove() 删除元素

[英]jQuery remove element with next() and remove()

I am using jQuery to remove an element with the class named " added " There are multiple elements with this class name.我正在使用 jQuery 删除名为“已added ”的 class 元素 有多个元素具有此 class 名称。

$(".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>");
    }
});

Here is the HTML:这是 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>

When I click the no radio button the element does not get removed, what am I doing wrong?当我点击无单选按钮时,元素没有被删除,我做错了什么?

Your jQuery is wrong for removing the element.您的 jQuery 删除元素是错误的。 In $(this).parent().next(".added").remove();$(this).parent().next(".added").remove(); , $(this) is the input element, so it's parent is just the .radio-group element. , $(this)是输入元素,所以它的父元素只是.radio-group元素。 You need to change it to $(this).parents('.radio-wrapper').next(".added").remove();您需要将其更改为$(this).parents('.radio-wrapper').next(".added").remove();

Even above will not work because there is a <div> between .radio-wrapper and .added , to make it work, you need to use next() twice: $(this).parents('.radio-wrapper').next().next(".added").remove();上面的内容也不起作用,因为.radio-wrapper.added之间有一个<div> ,要使其起作用,您需要使用next()两次: $(this).parents('.radio-wrapper').next().next(".added").remove();

I dont know, where what's exactly the .steps-row-first the element我不知道.steps-row-first元素到底在哪里

but try using parents to get back then chose the parent's siblings to target your div with added class as below:但是尝试使用父母返回然后选择父母的兄弟姐妹来定位你的 div 添加 class 如下:

....
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>"); } });

you can use find() to find all class.added and remove it您可以使用 find() 查找所有 class.added 并将其删除

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

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