Javascript for loop scope takes last variable

前端 未结 4 1690
清酒与你
清酒与你 2020-12-22 02:09

This works:

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

    if(open){
      $(\'#toggle_\' + most          


        
相关标签:
4条回答
  • 2020-12-22 02:28

    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

    0 讨论(0)
  • 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()); 
    });
    
    0 讨论(0)
  • 2020-12-22 02:50

    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).

    0 讨论(0)
  • 2020-12-22 02:52

    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) });
    })
    
    0 讨论(0)
提交回复
热议问题