2013-04-20 128 views
4

我想用jQuery獲取DOM元素,但我只想在DOM中向後看。通過遍歷DOM向後獲取最接近的元素

因此,假設我有以下HTML結構:

<div id="content"> 
    <div id="first-module" class="module"> 
     <h3>Some Module</h3> 
     <p>Lorem ipsum... </p> 

     <div id="some-other-content"> 
      <div id="second-module" class="module"> 
       <h3>Some other module</h3> 
       <p>Dolor sit amet...</p> 
       <button class="trigger">Trigger 1</button> 
      </div> 
     </div> 

     <button class="trigger">Trigger 2</button> 
     <div id="third-module" class="module"> 
      <h3>Another module</h3> 
     </div> 
    <div> 
</div> 

$('.trigger').click(function() { 
    // Traverse DOM to find closest .module class 
}); 

所以,當我在Trigger 1按鈕點擊我希望它找到div ID爲second-module

當我Trigger 2點擊我希望它找到div ID爲first-modulesecond-module,因爲它嵌套深於Trigger 2按鈕。

有沒有這個jQuery函數?

回答

4

嘗試使用.closest()

$('.trigger').click(function() { 
    $(this).closest('.module'); 
}); 
+0

不錯,由於某種原因,我雖然「最接近」會走兩邊。但這是完美的。 – Vivendi 2013-04-20 17:01:15

4

是的,我們確實有.closest()此:

$('.trigger').click(function() { 
    // Traverse DOM to find closest .module class 
    var id = $(this).closest('.module').attr('id'); 
    alert(id); 
}); 

DEMO HERE

+0

這裏是一個小提琴http://jsfiddle.net/JzWNQ/4/ – Mortalus 2013-04-20 16:52:57

1

另一種方式來訪問它使用parent selector

$('.trigger').click(function() { 
    console.log($(this).parent('.module').attr('id')); 
    // Traverse DOM to find closest .module class 
}); 
+0

雖然用'parent()',但是這會返回零個或多個元素,不像'nearest',它返回零或一個元素。這也意味着'parent'回溯到文檔根目錄,不像'nearest'。所以當你只需要一個元素時,'parent'可能會帶來太多開銷。 – w00 2013-04-20 17:02:40

+0

@ w00我想你是在談論父母(),但我正在使用父母。 .parents()和.parent()方法是相似的,只不過後者只在DOM樹上傳遞一個單獨的級別。 – PSL 2013-04-20 17:13:14

+0

啊你說得對,我以爲'parent()'這樣做了,但是它是'parents()'。我的錯。 – w00 2013-04-20 21:42:09