jQuery中最靠近的祖先节点 [英] nearest ancestor node in jQuery

查看:107
本文介绍了jQuery中最靠近的祖先节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的JavaScript体验中,我发现这是一个非常常见的任务,用一些条件(标签名,类,...)搜索最近的一个元素的祖先。
可以将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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆