2010-05-24 45 views
5

我們可以使用closest(selector)來查找匹配選擇器的第一個祖先元素。它將向上移動 DOM樹,直到它找到匹配的選擇器。但是,如果我想要在下調 DOM樹,直到它找到匹配選擇器?有沒有這樣做的jQuery功能?還是我需要使用廣度優先搜索來實現?如何用jQuery找到最接近的後代(匹配選擇器)?

舉個例子。對於下面的DOM樹,

<div id="main"> 
    <div> 
     <ul><!-- I want to match this ul --> 
      <li> 
       <ul><!-- but not this ul --> 
       </ul> 
      </li> 
     </ul> 
     <ul><!-- and match this ul --> 
     </ul> 
    </div> 
</div> 

如何做類似$('#main').closestDescendants('ul')

回答

1

像這樣的東西可能就足夠了:

$('#main ul:not(#main ul ul)') 

如果你需要更多的東西,然後準確您可以使用each()來迭代元素列表,計算到#main的最短路徑,並過濾掉路徑比這更長的元素。

+0

這要求您有一些錨點#main,而不是將其定位到某個上下文元素。有沒有一種方法可以編寫它,以便它只相對於一個範圍,並且它不匹配匹配基於高於上下文範圍的祖先的元素? – 2011-03-06 01:42:59

0

您想要匹配的元素是否始終是div的孩子?如果是這樣,你可以使用.children('ul')語法來匹配。這將是最好把一個ID /類的DIV,這樣你就可以做到以下幾點...

$('#menu').children('ul'); 

<div id="main"> 
    <div id="menu"> 
     <ul><!-- I want to match this ul --> 
      <li> 
       <ul><!-- but not this ul --> 
       </ul> 
      </li> 
     </ul> 
     <ul><!-- and match this ul --> 
     </ul> 
    </div> 
</div> 
+0

$('#main')和它最近的ul後代之間的高低差別可能會有所不同,並且只有$('#main')具有確定的id。 – powerboy 2010-05-24 03:41:27

0

我有同樣的問題,需要一個更通用的解決方案,所以我寫了一個函數,並決定把它打包爲jQuery plugin。我知道這個帖子很老,但請看看,讓我知道你的想法。

1

因此,最接近的兒童插件鏈接被打破了我。這裏有一個實現:

$.fn.nearest = function(selector) { 
    var nearest = $(), node = this, distance = 10000; 
    node.find(selector).each(function(){ 
     var n = $(this), 
      d = n.parentsUntil(node).size(); 
     if (d < distance) { 
      distance = d; 
      nearest = n; 
     } else if (d == distance) { 
      nearest = nearest.add(this); 
     } 
    }); 
    return nearest; 
}; 
+1

在jQuery的傳統中,如果選擇器失敗,返回undefined並不是標準。最好返回一個空的jQuery對象。在上面的代碼片段中,正確初始化'nearest',即:用'var nearest = $()'替換'var nearest'。 – eleotlecram 2012-10-26 11:15:12

+0

你說得對,很好。 – 2012-10-26 15:39:06

+0

jQuery的前一個插件數據庫丟失了。 「clostestChild」插件現在可以在名爲「closestDescendant」的新插件數據庫中使用http://plugins.jquery.com/closestDescendant/ – TLindig 2013-04-09 20:46:23