如何创建递归jQuery函数?

时间:2012-02-16 22:46:38

标签: jquery jquery-plugins recursion

我正在尝试制作一个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);

1 个答案:

答案 0 :(得分: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);
相关问题