2012-02-16 9 views
1

私は正方形を取るjQueryプラグインを作成しようとしていますが、その中に3つの正方形を入れておき、それらの3つの正方形内に3つの小さな正方形を置きます。私は、例えば、必要とするか、または完全なコードが欲しい、これが把握するために私自身の問題であるとして、私は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); 
関連する問題