JQuery callback question

I am trying to assign a different number to various 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); } ) } ); } 

Every time I run this section of code, I am equal to 5 for each ajaxDiv call, because it calls a global variable. I am not sure if I can change the scope of me or if there is a way to print the value in the change function. Any ideas?

Thank you in advance! Happy Thanksgiving

Andrew

0
source share
1 answer

All callback functions refer to the same variable i , and they are executed when the loop is complete.

You need to write the variable i in 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); } 
+3
source

All Articles