2017年5月26日 星期五

$.closestChildren 找到符合過濾條件最接近的子孫

 //for backbone(取代 find)
(function ($) {
    // 找到符合過濾條件最接近的子孫
    $.fn.closestChildren = function (selector) {
        debugger;
        var self = this;
        this.each(function (i, dom) {

            $find = $.closestChildren(dom, selector);
            self[i] = $find.get(0);
        });
        /*------------------------------------*/
        var resultList = this.toArray().filter(function (item) {
            return (item != null);
        });
        for (var i = 0; i < this.length; i++) {
            if (resultList[i]) {
                this[i] = resultList[i];
            } else {
                delete this[i];
            }
        }

        this.length = resultList.length;
      
        return this;
    };
    /* ====================================================================== */
    $.closestChildren = function (dom, selector) {
        var domList = [];
        var target = find(dom);
        /* ---------------------------------- */
        if (target.length) {
            // 第一輪就找到
        } else {
            // 廣域搜尋
            for (var i = 0; i < domList.length; i++) {
                target = find(domList[i]);
                if (target.length > 0) {
                    break;
                }
            }
        }
        /* ---------------------------------- */
        function find(dom) {
            var $findList = $(dom).children(selector);

            if ($findList.length) {
                // 有找到
            } else {
                // 沒找到
                var childList = $(dom).children().toArray();
                domList = domList.concat(childList);
            }
            return $findList;
        }

        domList = [];
        return target;
    };
})(jQuery);