問題描述
我正在嘗試創建一個循環來創建許多函數,以便當用戶單擊拇指向上按鈕時,它會運行正確的 .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 循環無法正常工作?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!