2012-02-16 2 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) 인 플러그인 기본 메소드에서 호출하고 원하는 깊이가 될 때까지 깊이를 증가시키면서 반복합니다. 테스트되지 않은

:

(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); 
관련 문제