问题描述
我有这个代码:
$(#test)siblings('p')。remove ;
$(#test)。remove();
如何链接这段代码而不是分开编写?
您要使用在这种情况下:
$(#test)。siblings('p')。addBack ();
EDIT p>
首先,对于未来的访问者,如果你使用jQuery版本1.8-,你可能需要使用是
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
andaddBack
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()
forson
, we're telling jQuery that it need to go back fromson
to parent set which isdad
and add classadult
.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
onson
, we're telling jQuery to pushdad
andson
into the same room and add new classadult
andoldster
to both of them.这篇关于如何选择元素的父级和父级的兄弟姐妹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!