开发者

Pass an additional counter as parameter to a callback

I have a $("").load call to get data and dump it into several divs. Each div has a unique ID that I track with an index variable inside a For loop. I do several ajax calls inside this loop. In the call back function I want to use the value of this index again. However by the time the callback executes, the for loop is already finished the index variable always has the top limit开发者_运维知识库 value for the loop.

How can I pass the value to this index to the callback function?

EDIT:

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("");

           }
    );

}


You can wrap the entier loop body (or only the Ajax part) into an immediate function and pass the index as parameter:

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));
}

But you don't necessarily need the index. You can access the #eventX element inside the callback with this and the #dateX element is the next sibling. So you can simply do

for(var i=1;i<=daysNum;i++) {
    // other stuff
    $("#event"+index).load('...', function (){
        if($(this).html() === "") {
            $(this).next().empty();
        } 
    });
}

which is much more readable imo.


I think the issue is with the load callback function.

You are not missing the "#" before the event and date element selectors.

Try this version for the load callback:

function (data){            
    if($("#event"+i).html()=="")               
        $("#date"+i).html("");           
} 


for(var i=0; i<x; i++){
  Ajax(...,function(i) {
    // in callback !
    return function(data) {
      //Work with i:)
    };
  }(i));


I couldn't find any better way, but you can send index with ajax request with data parameter and then return it with the response in your callback.


You can pass the div unique index as either the div ID, the div's.data() or even in the metadata plugin. Another option is using closures.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜