How to return a value from a nested and anonymous function?

I have this JS code:

function paging() { 
    $('.paging li').click(function(e) {
        $('.paging li a').removeClass("active");
        $(this).find('a').addClass("active");
        $('#img-grp-wrap img').hide();

        var indexer = $(this).index(); 
        $('#img-grp-wrap img:eq('+indexer+')').fadeIn();    

        e.preventDefault();
        return indexer;
    });
}

var $cur_page = paging();
console.log($cur_page);

I would like to use the indexer value outside the function paging() but when I try doing console.log(), it just says undefined.

How do I structure this so that I can pass the index value of the link I clicked outside the function (which is the indexer variable)?

I'm a programming newbie so please bear with me.

Answers


It sounds like you really don't understand how event handlers work. When you install a click handler, you are telling the system that you would like it to call this function when a click happens some time in the future. Your function paging() runs and completes long, long before your element gets clicked on and your anonymous function gets called. As such, the paging() function CANNOT return the result of the click handler because the click hasn't even happened yet.

If you have some code that wants to use the indexer value then you need to call that code from the click handler and pass the value of indexer as an argument to the function you're calling. That might look something like this:

$('.paging li').click(function(e) {
    $('.paging li a').removeClass("active");
    $(this).find('a').addClass("active");
    $('#img-grp-wrap img').hide();

    var indexer = $(this).index(); 
    $('#img-grp-wrap img:eq('+indexer+')').fadeIn();    

    e.preventDefault();
    // call a function and pass it the indexer value
    processIndex(indexer);
});

Notice, I've also removed the paging function because you don't want to call that more than one time because it would install your event handlers again.


Need Your Help

SQL Conversion failed Error

sql sql-server sql-order-by

WhenI call this stored procedure: