Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

jquery - 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();
      $('#toggle_' + most + ' .plus').show();
    }else{
      $('#toggle_' + most + ' .plus').hide();
      $('#toggle_' + most + ' .minus').show();
    }

    $('#' + most + ' ol.tlist').toggle(open);
  };

  $('#toggle_mostviewed').click(function(){ toggler('mostviewed'); });
  $('#toggle_mostshared').click(function(){ toggler('mostshared'); });
  $('#toggle_mostrecent').click(function(){ toggler('mostrecent'); });

But this does not:

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

    if(open){
      $('#toggle_' + most + ' .minus').hide();
      $('#toggle_' + most + ' .plus').show();
    }else{
      $('#toggle_' + most + ' .plus').hide();
      $('#toggle_' + most + ' .minus').show();
    }

    $('#' + most + ' ol.tlist').toggle(open);
  };

  var t = ['mostviewed','mostshared','mostrecent'];
  for(var i = 0 ; i  < t.length; i++ ){
    var j = t[i];
    $('#toggle_' + j).click(function(){ toggler(j) });
  }

Is like the for loop was "replaced" by:

  $('#toggle_mostrecent').click(function(){ toggler('mostrecent'); });

i.e. the last iteration is the only that counts.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...