jQuery回调问题 [英] JQuery callback question
本文介绍了jQuery回调问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试为jquery中的不同回调函数分配一个不同的数字.
I'm trying to assign a different number to different callback functions in jquery.
for (i=o;i<types.length;i++) {
$('#ajax'+types[i]+'Div').html('Loading...').load('searchAjax.php','new=u',function () { $(this).find('select').change( function() { AjaxDiv(i); } ) } );
}
每次我运行这段代码时,对ajaxDiv的每次调用我都是5,因为它正在调用全局变量.我不确定是否可以更改i的范围,或者是否可以在change函数中打印值.有什么想法吗?
Everytime I run this section of code, i is 5 for each call to ajaxDiv because it is calling a global variable. I'm not sure if I can either change the scope of i or if there's a way to print the value in the change function. Any ideas?
先谢谢您!感恩节快乐!
Thank you in advance! Happy Thanksgiving!
安德鲁
推荐答案
所有回调函数都引用同一个i
变量,并且它们在循环完成时执行.
The callback functions all refer to the same i
variable, and they are executed when the loop is finished.
您必须在循环中捕获i
变量:
You have to capture the i
variable on the loop:
for (i=o;i<types.length;i++) {
(function (i) {
$('#ajax'+types[i]+'Div').html('Loading...').load('searchAjax.php','new=u',
function () {
$(this).find('select').change( function() { AjaxDiv(i); } )
} );
})(i);
}
这篇关于jQuery回调问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文