Similar to jQuery .closest() but traversing descendants?

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

    The following plugin returns the nth closest descendants.

    $.fn.getNthClosestDescendants = function(n, type) {
      var closestMatches = [];
      var children = this.children();
    
      recursiveMatch(children);
    
      function recursiveMatch(children) {
        var matches = children.filter(type);
    
        if (
          matches.length &&
          closestMatches.length < n
        ) {
          var neededMatches = n - closestMatches.length;
          var matchesToAdd = matches.slice(0, neededMatches);
          matchesToAdd.each(function() {
            closestMatches.push(this);
          });
        }
    
        if (closestMatches.length < n) {
          var newChildren = children.children();
          recursiveMatch(newChildren);
        }
      }
    
      return closestMatches;
    };
    

提交回复
热议问题