2013-11-26 65 views
2

我需要在$.each()循環內增加一個var計數器。這裏是我的代碼:迭代計數器裏面的jQuery .each()循環

ajaxCreateOrder = function(fileUrl, dataArray, numRecords) { 
    var loopIteration = 1; 
    var ajaxIterateDelay = 1000; 
    $.each(dataArray, function(key,val) { 
     setTimeout(function() { 
      doAjaxRequest(loopIteration, fileUrl, val, numRecords); 
     }, loopIteration * ajaxIterateDelay); 
     loopIteration++; 
    }); 
} 

所有工作正常,但loopIteration不會增加。我究竟做錯了什麼?謝謝。

回答

1

這是因爲wrong use of a closure variable in loop

ajaxCreateOrder = function (fileUrl, dataArray, numRecords, storeView) { 
    var ajaxIterateDelay = 1000; 
    $.each(dataArray, function (index, val) { 
     setTimeout(function() { 
      doAjaxRequest(index + 1, fileUrl, val, numRecords); 
     }, (index + 1) * ajaxIterateDelay); 
    }); 
} 

假設dataArray的是一個數組中,第一參數是index,可以使用它

+0

_it是因爲在錯誤的使用封閉變量的loop_ - 這只是一個簡單的乘法來獲得'setTimeout'的超時時間。當循環結束時,沒有變量被評估... – Andreas

+0

@Andreas'setIntration'用在setTimeout()中,它暫停了一個問題,因爲它會有循環的最後一個值 –

+0

你說得對,如果錯過了'loopIteration'發生:( – Andreas

1
setTimeout(function() { 
     // ... 
     loopIteration++;     // inside 
    }, loopIteration * ajaxIterateDelay); 
              // not here 
+0

謝謝,那可能是:) – Jongosi