简体   繁体   English

jQuery隐藏所有子代的父代

[英]jQuery hide parent with all of its children

I am trying to delete parent element with all of its children after one of the child is actually clicked on HTML: 我实际上是在HTML上点击了子元素之一之后,尝试删除其所有子元素的父元素:

<div class='container'>
    <span class='content' id='1'>Lorem</span>
    <span class='content' id='2'>Ipsum</span>
    <span class='content' id='3'>Dolor</span>
    <span class='content' id='4'>Sit</span>
    <span id='delete'>Delete</span>
</div>

jQuery: jQuery的:

$("#delete").click(function() {
  var name = $(this).siblings("#1").text();
  var surname = $(this).siblings("#2").text();
  var add = $(this).siblings("#3").text();
  var all = $(this).siblings("#4").text();
  $.ajax({
    data: {
      'name': name,
      'surname': surname,
      'add': add,
      'all': all
    },
    success: function(data) {
      $(this).siblings().remove(); // context of 'this' lost? doesnt work
      $(this).parent().remove();

    }
  });
});

Bear in mind. 记住。 There is a few of those elements with class container having the exact same structure. container中的一些元素具有完全相同的结构。

Store the value of this in a variable outside of the success callback scope. 存储的值this在成功回调范围的变量之外。

$("#delete").click(function() {
  var self = this;
  // ...

  $.ajax({
    data: {},
    success: function(data) {
      $(self).siblings().remove();
      $(self).parent().remove();
    }
  });
});

It's worth pointing out that removing the parent element will also remove all of the children elements anyways. 值得指出的是,删除父元素也将删除所有子元素。 This means that you don't have to remove the sibling elements before removing the parent element. 这意味着您在删除父元素之前不必删除兄弟元素。

$(self).parent().remove(); // No need to remove siblings, they will be removed.

However, you may want to remove the sibling elements, and then unwrap the element. 但是,您可能想要删除同级元素,然后解包该元素。 In doing so, you can preserve the #delete element (if that's what you're trying to do). 这样,您可以保留#delete元素(如果您要这样做)。

$(self).siblings().remove();
$(self).unwrap();
 $("#delete").click(function() {
  var elem = $(this);
  //Other code
  $.ajax({
    data: {},
    success: function(data) {
      elem.siblings().remove();
      elem.closest(".container").remove();
    }
  });

你有没有尝试过这样的事情

 $(".content").children().hide(); 

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

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