我有一个$("").load调用来获取数据并将其转储到几个div中.每个div都有一个唯一的ID,我跟踪For循环中的索引变量.我在这个循环中做了几个ajax调用.在回调函数中,我想再次使用该索引的值.但是,在回调执行时,for循环已经完成,索引变量始终具有循环的上限值.
如何将值传递给此索引到回调函数?
编辑:
for (var i=1;i<=daysNum;i++)
{
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + i);
var tmd=(tomorrow.getMonth()+1)+'/'+(tomorrow.getDate())+'/'+tomorrow.getFullYear();
var tmdurl=(tomorrow.getMonth()+1)+'%2F'+(tomorrow.getDate())+'%2F'+tomorrow.getFullYear();
$("#events").append("<div><div id='event"+i+"'></div><div id='date"+i+"'>"+tmd+"</div></div>");
$("#event"+i).load(seicalendarurl+"/calendar.aspx?CalendarDate="+tmdurl+"&CalendarPeriod=Day .ms-cal-tdayitem, .ms-cal-alldayevent"
, function (data){
if($("event"+i).html()=="")
$("date"+i).html("");
}
);
}
Run Code Online (Sandbox Code Playgroud)
您可以将entier循环体(或仅Ajax部分)包装到立即函数中,并将索引作为参数传递:
for(var i=1;i<=daysNum;i++) {
// other stuff
(function(index) {
$("#event"+index).load('...', function (){
if($("#event"+index).html() === "") // you need `#` here too!
$("#date"+index).empty(); // you need `#` here too!
});
}(i));
}
Run Code Online (Sandbox Code Playgroud)
但是你不一定需要索引.您可以访问#eventX回调内this的#dateX元素,元素是下一个兄弟.所以你可以做到
for(var i=1;i<=daysNum;i++) {
// other stuff
$("#event"+index).load('...', function (){
if($(this).html() === "") {
$(this).next().empty();
}
});
}
Run Code Online (Sandbox Code Playgroud)
这是更可读的imo.