jQuery中最靠近的祖先节点 [英] nearest ancestor node in jQuery
问题描述
可以将jquery的parents()方法做好吗?父母()的返回元素的顺序是可预测的吗?是从顶到底还是从底到顶?
目前我使用这个效用函数:
函数祖先(elem,selector){
var $ elem = $(elem).parent();
while($ elem.size()> 0){
if($ elem.is(selector))
return $ elem;
else
$ elem = $ elem.parent();
}
返回null;
}
有人可以告诉我有没有聪明的方法来做这项工作? / p>
编辑:由于jQuery 1.3,这个内置的是 nearest()
功能。例如: $('#foo')。最近('。bar');
yep - parents()遍历树。
< div id =a> ;
< div id =b>
< p id =c>
< a id =d>< / a>
< / p>
< / div>
< / div>
$('#d')父母(div:first );
将选择div b。
In my javascript experience, I found that is a very common task "searching the nearest ancestor of an element with some condition (tag name, class,...)". Can the parents() method of jquery do the job? The order of returned elements of parents() is predictable? Is top-to-bottom or bottom-to-top? For the moment I use this utility function:
function ancestor(elem, selector) {
var $elem = $( elem ).parent();
while( $elem.size() > 0 ) {
if( $elem.is( selector ) )
return $elem;
else
$elem = $elem.parent();
}
return null;
}
Can someone tell me if there is a clever way to do the job?
Edit: Since jQuery 1.3, this has been built in as the closest()
function. eg: $('#foo').closest('.bar');
yep - parents() traverses up the tree.
<div id="a">
<div id="b">
<p id="c">
<a id="d"></a>
</p>
</div>
</div>
$('#d').parents("div:first");
will select div b.
这篇关于jQuery中最靠近的祖先节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!