使用jQuery是否有找到最远(最深或嵌套最多)子元素的方法? [英] Using jQuery is there a way to find the farthest (deepest, or most nested) child element?

查看:107
本文介绍了使用jQuery是否有找到最远(最深或嵌套最多)子元素的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一组元素:

<div class="start">
    <div>
        <span>Text 1</span>
    </div>
</div>

<div class="start">
    <span>
        <div>
            <span>Text 2</span>
        </div>
        <div>
            <div>
                <span>Text 3</span>
            </div>
        </div>
    </span>
</div>

(使用jQuery)检索嵌套最多的子元素(在这种情况下,跨度为文本1"和文本3")的最佳方法是什么,而又不事先知道元素的具体结构是什么?

What is the best way (using jQuery) to retrieve the most nested child elements (in this case the spans "Text 1" and "Text 3") without knowing what the element structure will be beforehand specifically?

这是我正在使用的 jsFiddle .

此外,我很抱歉以前是否曾问过这个问题,但是我找不到类似此问题的任何东西.

Also, I apologize if this has been asked before, but I couldn't find anything like this question specifically.

推荐答案

这里是使用我之前编写的treeWalk函数的实现,然后将其包装在jquery方法中,该方法在传入的jQuery中查找每个项目的最深后代对象,并返回一个包含这些节点的新jQuery对象.

Here's an implementation that uses a treeWalk function I had written earlier and then wraps it in a jquery method that finds the deepest descendant of each item in the passed in jQuery object and returns a new jQuery object containing those nodes.

使用递归和许多jQuery的解决方案可以用更少的代码来完成,但可能会更慢.这是基于对树进行遍历的通用本机JS树遍历功能.

A solution with recursion and lots of jQuery can be done with lots less code, but it will likely be slower. This is based on a generic native JS tree walk function that walks a tree.

使用比OP的HTML更复杂的HTML测试用例进行工作的演示: http://jsfiddle.net/jfriend00/8tC3a/

Working demo with more complicated HTML test case than the OP's HTML: http://jsfiddle.net/jfriend00/8tC3a/

$.fn.findDeepest = function() {
    var results = [];
    this.each(function() {
        var deepLevel = 0;
        var deepNode = this;
        treeWalkFast(this, function(node, level) {
            if (level > deepLevel) {
                deepLevel = level;
                deepNode = node;
            }
        });
        results.push(deepNode);
    });
    return this.pushStack(results);
};

var treeWalkFast = (function() {
    // create closure for constants
    var skipTags = {"SCRIPT": true, "IFRAME": true, "OBJECT": true, "EMBED": true};
    return function(parent, fn, allNodes) {
        var node = parent.firstChild, nextNode;
        var level = 1;
        while (node && node != parent) {
            if (allNodes || node.nodeType === 1) {
                if (fn(node, level) === false) {
                    return(false);
                }
            }
            // if it's an element &&
            //    has children &&
            //    has a tagname && is not in the skipTags list
            //  then, we can enumerate children
            if (node.nodeType === 1 && node.firstChild && !(node.tagName && skipTags[node.tagName])) {                
                node = node.firstChild;
                ++level;
            } else if (node.nextSibling) {
                node = node.nextSibling;
            } else {
                // no child and no nextsibling
                // find parent that has a nextSibling
                --level;
                while ((node = node.parentNode) != parent) {
                    if (node.nextSibling) {
                        node = node.nextSibling;
                        break;
                    }
                    --level;
                }
            }
        }
    }
})();

var deeps = $(".start").findDeepest();

deeps.each(function(i,v){
    $("#results").append(
        $("<li>").html($(v).prop("tagName") + " " + $(v).html())
    );
});

这篇关于使用jQuery是否有找到最远(最深或嵌套最多)子元素的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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