开发者

JQuery callback question

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开发者_如何学JAVA); } ) } );
}

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!

Andrew


The callback functions all refer to the same i variable, and they are executed when the loop is finished.

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜