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 循环无法正常工作?


- PHP - if 语句中的倒序 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01