2013-07-26 15 views

回答

2

這取決於你來自哪裏。 parent()將始終選擇直接父元素,addBack()的結果取決於先前選擇的結果:

.addBack([選擇器])

返回:jQuery的 說明:將前一組將堆棧上的元素設置爲當前集合,可以通過選擇器進行過濾。

看看下面的jsfiddle例如: http://jsfiddle.net/vGAq5/2/

第一個提醒會選擇排名第二的所有後續的兄弟姐妹,加回第二把交椅。 第二個aler會選擇第二個所有後面的兄弟,並取其父(而不是將其添加到結果集)。

2

完全不同的方法:

addBack() - add the current selection to the previous one and merges those selections 

parent() - selects the direct parent of the current selection 

檢查的官方文檔:

http://api.jquery.com/addBack/

http://api.jquery.com/parent/

基本例如:

考慮HTML:

<div id="parent"> 
    <div id="child"> 
    </div> 
</div> 

的javascript:

console.log($('#child').parent()); // return the div#parent selection 

console.log($('#child').addBack()); // return the div#child selection - it merges the div#child with the previous selection (which happens to be empty) 
+0

addBack的API說「將堆棧中的前一組元素添加到當前集合」。 – nipponese

+0

@nipponese - 這是一樣的..添加A到B是相同的添加B到A ..或者我不明白評論 –

1

parent結果得到的DOM,它是當前選擇的直接DOM父,而addBack獲得先前的選擇,當你在做的jQuery鏈接。

使用下面的例子:

<div class="the-one"> 
    <div class="child-1"> 
    <div class="grandchild-1"></div> 
    <div class="grandchild-2"></div> 
    </div> 
    <div class="child-2"></div> 
    <div class="child-3"></div> 
</div> 

如果運行$('.the-one').find('.grandchild-1').parent()你會得到child-1

如果您運行的是$('.the-one').find('.grandchild-1').addBack(),您將獲得the-onegrandchild-1

addBack通常用於橫向鏈接DOM時,並且想要簡單的方法返回到上一個選擇並進行另一個橫向。

相關問題