views:

1453

answers:

4

How can I call a function from inside the function, so it becomes recursive? Here is my code, I have added a comment where I would like to start the recursion:

$('a.previous-photos, a.next-photos').click(function() {
    var id = $('#media-photo img').attr('id');
    var href = $(this).attr('href');
    href = href.split('/');
    var p = href[href.length - 1];
    var url = '/view/album-photos/id/' + id + '/p/' + p;

    $.get(url, function(data) {
        $('.box-content2').replaceWith('<div class="box-content2"' + data + '</div>');
    });

    // here I want to call the function again

    return false;
});
+2  A: 

Something of this sort should do the trick, but there ought to be a nicer way to set it up:

function myfunc() {
    var id = $('#media-photo img').attr('id');
    var href = $(this).attr('href');
    href = href.split('/');
    var p = href[href.length - 1];
    var url = '/view/album-photos/id/' + id + '/p/' + p;

    $.get(url, function(data) {
        $('.box-content2').replaceWith('<div class="box-content2"' + data + '</div>');
    });

    if(!cond){//you need a condition, or it'll recurse indefinitely.
       myfunc();
    }

    return false;
}

$('a.previous-photos, a.next-photos').click(function(){myfunc();});
krdluzni
+7  A: 

You can make a recursive call to an anonymous function by doing

arguments.callee( .... );

See here for more info.

jimr
Would it be possible to get a complete sample? I haven't been able to make this work, yet...
krdluzni
The linked site has an example of creating an anonymous recursive factorial function.
jimr
+1  A: 

From Javascript 1.2 onwards you can use arguments.callee(...) to effect a recursive call to an anonymous function

// here I want to call the function again
arguments.callee();
Paul Dixon
A: 

Put your code in a jQuery plugin format and call itself for example...

For a detailed example click the following link

http://www.mattloinfo.com/javascript/jquery-recursive-function/

(function($) {
$.fn.togglethis = function () {
    $(this).animate({opacity:"1.0"}, 1000, function() {
        /* Code Here */
        return $(this);
    });

}
})(jQuery);
$(document).ready(function() {
    $("#togglethis").togglethis();
});

Insert your desired code where the comment is.

Matt