Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Jquery Loop not working correctly?

I am trying to create a loop to create many functions so that when a user clicks the thumb up button it runs the correct .php document. It works great when I remove the loop and just give var i a specific number but as soon as i try to make it into a loop, at the alert(i) i get 10 on the first loop.

 var i=1;
 while ( ++i < 10 ) {
    $('#thumbup' + i).click(function() {
        var userid = $('#theuser' + i).text();
        var url = "_thumbup.php?userid=" + userid;
        //alert(url);

        $('#thumbup' + i).hide();
        $('#thumbdown' + i).hide();

        $("#toggle").css("display","block");
        alert(i); // Give me 10 on first loop?!?

        // get the URL
        http = new XMLHttpRequest(); 
        http.open("GET", url, true);
        http.send(null);

        // prevent form from submitting
        return false;   

    }); 
  }
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This is a classical problem : by the time your callbacks are called, i has the value of end of loop.

Here's how you can fix it :

var i=1;
while ( ++i < 10 ) {
   (function(i){
      // your current code
   })(i);
}

It works because the internal function creates a scope when it is called, and this scope contains the value of i you want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...