Jquery Loop not working correctly?(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 循环无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Jquery 循环无法正常工作?


基础教程推荐
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- 将变量从树枝传递给 js 2022-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- php中的foreach复选框POST 2021-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- Web 服务器如何处理请求? 2021-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- php中的PDF导出 2022-01-01