Similar to jQuery .closest() but traversing descendants?

后端 未结 16 722
情书的邮戳
情书的邮戳 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:47

    According to your definition of closest, I've written the following plugin:

    (function($) {
        $.fn.closest_descendent = function(filter) {
            var $found = $(),
                $currentSet = this; // Current place
            while ($currentSet.length) {
                $found = $currentSet.filter(filter);
                if ($found.length) break;  // At least one match: break loop
                // Get all children of the current set
                $currentSet = $currentSet.children();
            }
            return $found.first(); // Return first match of the collection
        }    
    })(jQuery);
    

提交回复
热议问题