【发布时间】:2024-12-14 07:15:02
【问题描述】:
我在for 循环中放置了一个异步回调函数(类似于$.ajax)。它看起来或多或少像(编辑:更新的代码,见 cmets):
var i = 0;
for ( ; i < 5; i++ ) {
(function( index ) {
$.ajax({
url: "",
success: function() {
console.log( index );
}
});
})( i );
}
它起作用了,但是 JSHint 给了我一个警告,比如:
“不要将函数放在循环中”
通常我可以将我的 callback 函数放在我的循环之外,并在每次迭代时调用该函数。不幸的是,我需要访问在循环内分配的变量(例如i)。所以我正在寻找一种解决方案来执行以下操作:
var i = 0;
function callback( data ) {
// I want to have access to "i" (0, 1, 2, 3, 4) and the AJAX "data"
// in this function. But I only have access to "data", because "i"
// will always be 5
}
for ( ; i < 5; i++ ) {
$.ajax({
url: "",
success: callback
});
}
【问题讨论】:
-
好吧,在您的第一个示例中,
i在所有回调中也将是5。见JavaScript closure inside loops – simple practical example。 -
你必须循环......你不能发送一个包含所有数据的请求吗?
-
只需修复您的 for 循环并将此行添加到您的 ajax 调用
async : false -
@RobertRozas 嗯...请不要那样做。
-
@KevinB,我误解了这个问题,抱歉 :)
标签: javascript jquery asynchronous jshint