Skip to content Skip to sidebar Skip to footer

Javascript For Loop Scope Takes Last Variable

This works: var toggler = function(most){ var open = $('#toggle_' + most + ' .minus').is(':visible'); if(open){ $('#toggle_' + most + ' .minus').hide(); $('#

Solution 1:

Your loop is constructed incorrectly. When you want to set a variable in a loop to access an element of an array or object, this is the correct syntax:

var test = [];
for(var i = 0; i < test.length; test++)
    (function(index){
        // do cool stuff with test[index]
    })(i);

This creates a closure over the variable i. If you aren't familiar with the syntax, here's what happens:

1) We define a closure (the opening ()'s after the for statement)

2) We define an anonymous function to take the index parameter

3) We pass the index into the closure (i.e. we execute the function)with the final set of ()'s.

These three steps happen for every iteration of the loop. If you don't use the closure to capture the index value, then when the array access is actually made, the index in this example would be +1 too many, and cause errors at runtime.

Cheers

Solution 2:

it is because of wrong use of a closure variable in a loop

In this case since you are iterating through an array, you can use $.each()

var t = ['mostviewed','mostshared','mostrecent'];
$.each(t, function(_,most){
    $('#toggle_' + most).click(function(){ toggler(most) });
})

Solution 3:

You said:

$('#toggle_' + most).click(function(){ toggler(most) });

but I think this is what you meant:

$('#toggle_' + j).click(function(){ toggler(j) });

(you defined j but then used most instead).

Solution 4:

Why not do something like:

$('#toggle_mostviewed, #toggle_mostshared, #toggle_mostrecent').click(function({
    toggler((this.id).split("_").pop()); 
}); 

Or even better, give them a class "toggle" (and also leave the IDs in the html) and then:

$('.toggle').click(function({
    toggler((this.id).split("_").pop()); 
});

Post a Comment for "Javascript For Loop Scope Takes Last Variable"