且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何选择元素的父级和父级的兄弟姐妹

更新时间:2023-11-30 10:27:28

您要使用 addBack()在这种情况下:

  $(#test)。siblings('p')。addBack (); 
$ p>




EDIT p>

首先,对于未来的访问者,如果你使用jQuery版本1.8-,你可能需要使用 andSelf() addBack()的前身。



其次, end addBack 在这种情况下将执行相同的任务, 实际上是不同的观点。看看这个HTML:

 < div class =grandpa> 
< div class =dad>
< div class =son>
Test
< / div>
< / div>
< / div>

如果我们使用 end()

  $('。grandpa')
.find('。dad')
.find ('.son')
.addClass('youngster')
.end()
.addClass('adult')
.end()
.addClass ('oldster');

结果将如下所示:

 < div class =grandpa oldster> 
< div class =dad adult>
< div class =son youngster>
Test
< / div>
< / div>
< / div>

因此,当我们使用 end() son ,我们告诉jQuery它需要从儿子回到父集合 dad 并添加类 adult



但是当我们使用 addBack

  $('。grandpa')
.find '.dad')
.find('。son')
.addClass('youngster')
.addBack()
.addClass('adult')
.addBack()//这样做什么都不做,因为`addBack`没有遍历DOM元素
.addClass('oldster');

这将导致:

 < div class =grandpa> 
< div class =dad adult oldster>
< div class =son youngster adult oldster>
Test
< / div>
< / div>
< / div>

所以当我们调用 addBack c $ c> son ,我们告诉jQuery推送 dad son 同一房间,并向他们两个添加新类成人 oldster


I have this code:

$("#test").siblings('p').remove();
$("#test").remove();

How can I chain this code instead of writing it separately?

You want to use addBack() in this case:

$("#test").siblings('p').addBack().remove();


EDIT

Firstly, for future visitors, if you're using jQuery version 1.8-, you're probably need to use andSelf() which is the predecessor of addBack() for compatibility issues.

Secondly, both end and addBack will do the same task in this case but they're actually different perspective. Take a look at this HTML:

<div class="grandpa">
    <div class="dad">
        <div class="son">
            Test
        </div>
    </div>
</div>

If we're using end():

$('.grandpa')
    .find('.dad')
        .find('.son')
        .addClass('youngster')
        .end()
    .addClass('adult')
    .end()
.addClass('oldster');

The result will look like this:

<div class="grandpa oldster">
    <div class="dad adult">
        <div class="son youngster">
            Test
        </div>
    </div>
</div>  

So when we use end() for son, we're telling jQuery that it need to go back from son to parent set which is dad and add class adult.

But when we use addBack:

$('.grandpa')
    .find('.dad')
        .find('.son')
        .addClass('youngster')
        .addBack()
        .addClass('adult')
        .addBack() // This simply do nothing since `addBack` is not traverse up DOM element 
        .addClass('oldster');    

which will result in this:

<div class="grandpa">
    <div class="dad adult oldster">
        <div class="son youngster adult oldster">
            Test
        </div>
    </div>
</div>

So when we call addBack on son, we're telling jQuery to push dad and son into the same room and add new class adult and oldster to both of them.