一种在闭包中保持“for”变量的当前迭代的方法

时间:2013-01-11 14:04:04

标签: javascript closures

  

可能重复:
  Javascript closure inside loops - simple practical example

for (i=0; i<N; i++) {
   $.get("script"+ i +".jsp", function() {
       //I want to use i here
       //but by the time the ajax request comes back i==N, but I want the old i
   })
}

所以我得到了这个代码,我想知道是否有更好的方法来做这个比我的回复。 这不是关于jquery ajax调用,我知道有办法通过事件对象传递“i”,我想要一个比我想出的更好的通用解决方案。

1 个答案:

答案 0 :(得分:1)

制作一个自我执行的功能来保持我的作品,但非常难看:

for (i=0; i<N; i++) {
   (function(i) {
      $.get("script"+ i +".jsp", function() {
          //I want to use i here
          //but by the time the ajax request comes back i==N, but I want the old i
      })
   } (i) );
}