what i'm trying to do is to get a recordset of logos, have to arrays. 1: for the display 2: for the bank
i will display 10 logos on delay i will replace them. with the next 10 from the bank
for (var i=0;i<=10;i+=1){
$("#footerlogo-"+(i+1)).hide().append(DisplayArr[i]).fadeIn();
}
function ReplaceFooterLogos() {
var runon = 0;
var tempholder = "";
for (var i=0;i<=10;i+=1){
$("#footerlogo-"+(i+1)+"").fadeOut("fast",function(i){
BankArr.push(DisplayArr.shift());
DisplayArr.unshift(BankArr.shift());
$(this).html(DisplayArr[i]).fadeIn()
});
}
$("#mycaro开发者_如何学JAVAusel").delay(5000,function() { ReplaceFooterLogos() });
}
$("#mycarousel").delay(5000,function() { ReplaceFooterLogos() });
ignoe the delay function - i have it!
my question is why my the variable i is undefined? and how do i pass values to a callback?
my question is why my the variable i is undefined?
I suspect you'll find that it's DisplayArr[i]
that's undefined. i
should be 11
when the callbacks run.
When you create a closure (which is what your fadeOut
callback is), it has an enduring reference to a variable, not a copy of the value of the variable at that point in time. So all of your callbacks will see the same i
value, which will be its value after the loop is finished (11
). I'm guessing there's no DisplayArr[11]
. (More about closures here: Closures are not complicated.)
Here's how you can fix it:
function ReplaceFooterLogos() {
var runon = 0;
var tempholder = "";
for (var i=0;i<=10;i+=1){
$("#footerlogo-"+(i+1)+"").fadeOut("fast", createCallback(i));
}
$("#mycarousel").delay(5000,function() { ReplaceFooterLogos() });
function createCallback(index) {
return function(index){
BankArr.push(DisplayArr.shift());
DisplayArr.unshift(BankArr.shift());
$(this).html(DisplayArr[index]).fadeIn();
};
}
}
What we do there is use a factory function to build your fadeOut
callback, using its index
argument rather than i
. The callback will close over the index
argument that was given to createCallback
for the call that created the callback (so, a different one for each callback), and so it will use the value for that iteration of the loop (0
...10
inclusive).
精彩评论