父節點的遍歷

一、遍歷父節點 var ajQuery = {};html

function dir(elem, dir, until) {
    var matched = [],
            truncate = until !== undefined;
    while ((elem = elem[dir]) && elem.nodeType !== 9) {
        if (elem.nodeType === 1) {
            if (truncate) {
                if (elem.nodeName.toLowerCase() == until || elem.className == until) {
                    break;
                }
            }
            matched.push(elem);
        }
    }
    return matched;
}

jQuery.each({
    parent: function(elem) {
        var parent = elem.parentNode;
        return parent && parent.nodeType !== 11 ? parent : null;
    },
    parents: function(elem) {
        return dir(elem, "parentNode");
    },
    parentsUntil: function(elem, until) {
        return dir(elem, "parentNode", until);
    }
}, function(name, fn) {
    ajQuery[name] = function(until, selector) {
        return  fn(until, selector);
    };
});


$("#test1").click(function() {
    var item = $('.item-1');
    alert(item.parent()[0])
    alert(item.parents().length)
    alert(item.parentsUntil('body').length)
})

$("#test2").click(function() {
    var item = document.querySelectorAll('.item-1')[0]
    alert(ajQuery.parent(item))
    alert(ajQuery.parents(item).length)
    alert(ajQuery.parentsUntil(item, 'body').length)
})

樹結構:node

<!-- lang: html -->
<button id="test1">jQuery遍歷祖先</button>
<!-- lang: html -->
<button id="test2">模擬遍歷祖先</button>
<!-- lang: html -->

<!-- lang: html -->
<ul class="level-1">
<!-- lang: html -->
    <li class="item-i">I</li>
<!-- lang: html -->
    <li class="item-ii">II
<!-- lang: html -->
        <ul class="level-2">
<!-- lang: html -->
            <li class="item-a">A</li>
<!-- lang: html -->
            <li class="item-b">B
<!-- lang: html -->
                <ul class="level-3">
<!-- lang: html -->
                    <li class="item-1">1</li>
<!-- lang: html -->
                    <li class="item-2">2</li>
<!-- lang: html -->
                    <li class="item-3">3</li>
<!-- lang: html -->
                </ul>
<!-- lang: html -->
            </li>
<!-- lang: html -->
            <li class="item-c">C</li>
<!-- lang: html -->
        </ul>
<!-- lang: html -->
    </li>
<!-- lang: html -->
    <li class="item-iii">III</li>
<!-- lang: html -->
</ul>
相關文章
相關標籤/搜索