我们可以使用closest(selector)来查找与选择器匹配的第一个祖先元素。它在 DOM 树中向上移动,直到找到选择器的匹配项。但是,如果我想向下遍历 DOM 树,直到找到选择器的匹配项,该怎么办?有没有 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') 的操作?
请您参考如下方法:
所以,最近的Child插件链接对我来说已经损坏了。这是一个实现:
$.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;
};
