Jquery 循环无法正常工作? [英] Jquery Loop not working correctly?

查看:40
本文介绍了Jquery 循环无法正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个循环来创建许多函数,以便当用户单击拇指向上按钮时,它会运行正确的 .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.

这篇关于Jquery 循环无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆