2009-11-26 90 views
0

我想分配一个不同的数字给jquery中的不同回调函数。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的范围,或者是否有方法在更改函数中打印值。有任何想法吗?

预先感谢您!感恩节快乐!

安德鲁

+0

见http://stackoverflow.com/questions/1451009/javascript-infamous-loop-problem和http://stackoverflow.com/问题/ 341723 /事件处理程序,里面的一个JavaScript的循环需要封闭和约80个其他问题。 (提示:你需要关闭) – 2009-11-26 15:52:41

+0

虽然其他人肯定回答了这个问题,但另一个问题可能是你已经设置我等于字母O ... – Gausie 2009-11-26 16:34:40

+0

@ Gausie:o是新的0 – 2009-11-26 18:25:55

回答

3

回调函数都指向同一个i变量,当循环结束后,他们将被执行。

你必须捕捉到环路上i变量:

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

有多少次你在SO上解释过这个吗?我们非常需要这个FAQ。 – 2009-11-26 15:54:19

+4

是的,太多的时间,通过语言的常见问题将会很好... http://stackoverflow.com/questions/1734749/ http://stackoverflow.com/questions/643542/ http://stackoverflow.com/questions/1582634/ http://stackoverflow.com/questions/1331769/ http://stackoverflow.com/questions/1552941/ http://stackoverflow.com/questions/750486/ http:// stackoverflow问题/ 933343/ http://stackoverflow.com/questions/1579978/ http://stackoverflow.com/questions/1413916/ – CMS 2009-11-26 15:58:37

+1

圣洁的废话。永远不要删除该评论。那里有参考点。 – 2009-11-26 16:05:42