2012-02-16 86 views
1

我试图制作一个jQuery插件,它将采用一个正方形,在其中放置三个方块,然后在这三个方块内放置三个更小的正方形。我并不需要或想要完整的代码,因为这是我自己的问题搞清楚,但我无法弄清楚如何使一个jQuery插件调用本身,如:如何制作递归jQuery函数?

(function($){ 
    $.fn.squares = function(type) { 
     var recursionDepth = 1; 

     return this.each(function() { 
      var $this = $(this); 

      if (++ recursionDepth > 3) {console.log('rec lim');return;} 
      // put div.squares in $this 
      $('.square', $this).squares(); 
     }); 
    }; 
})(jQuery); 

回答

3

使用一个辅助函数,它实际工作并将深度作为参数。使用深度为1(或0)的插件main方法调用它,然后逐渐增加深度,直到达到所需的深度。

未经测试:

(function($){ 
    $.fn.squares = function(type) { 

     return this.each(function() { 
      doSquares($(this),1); 
     }); 

     function doSquares($square,depth) { // adds three squares to the current square and recurses over each to the appropriate depth 
      for (int i = 0; i < 3; ++i) { 
       var $newSquare = // add square to current square and return jQuery of the new square 
       if (depth < 3) { 
        doSquares($newSquare,depth+1); 
       } 
      } 
     } 
    }; 
})(jQuery);