简体   繁体   English

jQuery:将父级同级添加到当前匹配的元素中

[英]jQuery: Add Sibling of Parent to Current Matched Elements

I'm trying to - in one line - remove the parent element of a clicked element and the parent's lone sibling element. 我试图-在一行中-删除被单击元素的父元素和父元素的同级元素。 This is my two-liner solution here: 这是我的两层解决方案:

$(document).ready(function() {
    $('.close').click(function() {
        $(this).parent().siblings('.sibling').remove();
        $(this).parent().remove();
    });
});

Here's a working fiddle. 这是一个工作的小提琴。 I'm looking to avoid navigating the DOM twice since I've already found the parent of the clicked element when I remove the sibling, there's no reason I should be doing it again. 我希望避免两次浏览DOM,因为在删除同级时已经找到了clicked元素的父级,因此没有理由我应该再次进行操作。 I'm aware that I could wrap both the parent and sibling in an element and just remove that super element, but at this point I'd like to avoid that as well. 我知道我可以将父项和同级项都包装在一个元素中,然后删除该超级元素,但是在这一点上,我也想避免这种情况。

I've looked into using jQuery's .add() function, but I can't seem to get that to work. 我已经研究过使用jQuery的.add()函数,但似乎无法正常工作。 Thanks for your help! 谢谢你的帮助!

You're looking for .addBack() : 您正在寻找.addBack()

$(this).parent().siblings('.sibling').addBack().remove();

Demo 演示

  • andSelf is an equivalent to .addBack() for jQuery < 1.8 andSelf等效于jQuery <1.8的.addBack()

With .add() , you would have to store the parent in a variable to avoid traversing to it twice: 使用.add() ,您将不得不将父级存储在变量中,以避免遍历两次:

var $father = $(this).parent();
$father.siblings('.sibling').add($father).remove();
//one-liner without storing in a variable would traverse the DOM twice:
$(this).parent().siblings('.sibling').add($(this).parent()).remove();

As you can see, the addBack method is more practical in this case. 如您所见,在这种情况下, addBack方法更为实用。

In case the element's parent and the parent's sibling are the only elements inside their parent, you can also use: 如果元素的父级和父级的同级是其父级中唯一的元素,则还可以使用:

$(this.parentNode.parentNode).empty();

Demo 演示

The native parentNode property is a bit faster than jQuery's .parent() method. 原生parentNode属性比jQuery的.parent()方法要快一些。 It is up to which to use. 取决于使用哪个。


Note that such small traversing has very little overhead either way. 请注意,无论哪种方式,这种小的遍历都几乎没有开销。 Your original code and these versions have very little difference performance-wise. 您的原始代码和这些版本在性能方面几乎没有区别。

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

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