Jquery 循环无法正常工作?

2021-12-26 00:00:00 loops while-loop jquery php javascript

我正在尝试创建一个循环来创建许多函数,以便当用户单击拇指向上按钮时,它会运行正确的 .php 文档.当我删除循环并只给 var i 一个特定的数字时,它工作得很好,但是一旦我尝试将它变成一个循环,在 alert(i) 我在第一个循环中得到 10.

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;   

    }); 
  }

推荐答案

这是一个经典问题:当你的回调被调用时,i 的值是 end of loop.

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

解决方法如下:

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

之所以有效,是因为内部函数在调用时创建了一个作用域,而这个作用域包含了你想要的i的值.

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

相关文章