2010-10-13 30 views
6

乾草,我有一些類似這樣的標記jQuery鏈父(),有沒有更簡單的方法?

<div id="some-id"> 
    <h2><a href="#">Title</a></h2> 
</div> 

和一些jQuery的這樣

$(this).parent().parent().attr("id") 

$(這)是指 '一個' 標籤 'H2'

內有沒有更簡單的方法來選擇父div沒有使用父()兩次。我試過

$(this).parent("div").attr("id") 

但它沒有工作。

感謝

回答

14

您可以使用.closest(),像這樣:

$(this).closest("div").attr("id") 

You can test it here.parent("div")並不像看上去的那樣直觀,它得到直接如果它選擇相匹配,.closest()爬上父母直到它選擇相匹配。

請注意,(不適用於本示例)如果this選擇相匹配,則返回元素,它不開始和一次母體,它本身開始。

+0

.closest()只會向上移動嗎?或者它也會向下移動? – dotty 2010-10-13 09:08:47

+0

@dotty - 如果你想找到孩子使用'.find()',它只會發給父母,儘管你只能有一條父路徑,孩子可以有很多分支......所以要看你以後的樣子。 – 2010-10-13 09:10:09

相關問題