简体   繁体   English

如何使用jQuery遍历祖先?

[英]how do i traverse ancestors with jQuery?

How do I traverse ancestors with jQuery? 如何使用jQuery遍历祖先?

The current code is getting stuck in a recursive loop: 当前代码陷入了递归循环:

HTML: HTML:

<html>
    <body>
        <div>
            <ul>
                <li></li>
            </ul>
        </div>
    </body>
</html>

JS: JS:

function traverse($node){
  while ( $node.get(0) !== $("html").get(0) ) {
    console.log($node);
    traverse($node.parent());
  }

}

//traverse($("ul li"));

To observe the problem, un-comment the last line, but be warned that it may freeze your browser. 要观察该问题,请取消注释最后一行,但要警告它可能会冻结浏览器。

The same on JSFiddle: http://jsfiddle.net/WpvJN/1/ 在JSFiddle上也是如此: http : //jsfiddle.net/WpvJN/1/

You can get the collection with .parents() and iterate with .each() : 您可以使用.parents()获取集合,并使用.each()进行迭代:

$('ul li').parents().each(function () {
    console.log(this);
});

I expect you need to put a limit on the traverse in case the parent you seek is not an ancestor of where you started. 我希望您需要对遍历进行限制,以防您寻找的父母不是您开始的祖先。 Otherwise, you either end up in an endless loop or run out of parents. 否则,您要么陷入无休止的循环,要么就没父母了。

For example, a generic function to go from an element up to a parent with a particular tag name, you might do (not jQuery but I'm sure you can convert it if necessary): 例如,可以执行一个通用功能,从一个元素到具有特定标签名称的父级(不是jQuery,但我确定可以在必要时进行转换):

function upTo(tagName, el) {
  tagName = tagName.toLowerCase();

  // Make sure el is defined on each loop
  while (el && el.tagName && el.tagName.toLowerCase() != tagName) {
    el = el.parentNode;
  }
  return el;
}

An alternative is to check for el.parentNode and stop when there are no more. 一种替代方法是检查el.parentNode并在没有更多对象时停止。

There is always an HTML node in an HTML document, so as long as you don't start from the document node, you'll always get there. HTML文档中始终存在一个HTML节点,因此,只要您不从文档节点开始,就始终可以到达该节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM