Similar to jQuery .closest() but traversing descendants?

后端 未结 16 637
情书的邮戳
情书的邮戳 2020-12-07 15:13

Is there a function similar to jQuery .closest() but for traversing descendants and returning only closest ones?

I know that there is

16条回答
  •  时光说笑
    2020-12-07 15:50

    I cooked up this, no implementation for positional selectors (they need more than just matchesSelector) yet:

    Demo: http://jsfiddle.net/TL4Bq/3/

    (function ($) {
        var matchesSelector = jQuery.find.matchesSelector;
        $.fn.closestDescendant = function (selector) {
            var queue, open, cur, ret = [];
            this.each(function () {
                queue = [this];
                open = [];
                while (queue.length) {
                    cur = queue.shift();
                    if (!cur || cur.nodeType !== 1) {
                        continue;
                    }
                    if (matchesSelector(cur, selector)) {
                        ret.push(cur);
                        return;
                    }
                    open.unshift.apply(open, $(cur).children().toArray());
                    if (!queue.length) {
                        queue.unshift.apply(queue, open);
                        open = [];
                    }
                }
            });
            ret = ret.length > 1 ? jQuery.unique(ret) : ret;
            return this.pushStack(ret, "closestDescendant", selector);
        };
    })(jQuery);
    

    There is probably some bugs though, didn't test it very much.

提交回复
热议问题