问题
My brain its going to explode.. why this dont work? im trying to animate a few divs with time interval and trying to write less code but this dont work
var cargaCont = function(){
o = 1;
var animacion = function(i){
$('#page2txt'+i).animate({
height:'20'
},200,function(){
$('#page2img'+i).animate({
left:'0',
right:'0'
},200,function(){
i++;
return i;
});
});
}
while(o < 3){
setTimeout(function(){o = animacion(o);},200);
}
}
回答1:
The problem with this code:
while(o < 3){
setTimeout(function(){o = animacion(o);},200);
}
is by the time the functions delayed by setTimeout
are executed, o
is already 3 and therefore all calls to animacion
pass 3 instead of 1 and 2.
To circumvent this problem, you should "localize" the value of o
by using an immediate function.
while(o < 3){
//o out here is from cargaCont
(function(o){
//override o by naming the passed variable o
setTimeout(function(){
o = animacion(o); //now o refers to the local o
},200);
}(o)); //execute inner function, passing in o
}
This makes the o
used by the functions in setTimeout
to be bound to the o
of the local function and not the o
of the cargaCont
function.
回答2:
I'm not 100% sure what exactly you're going for but, I'm going to guess that you basically want to loop through some animations, maybe like this:
var cargaCont = function(){
var i = 1,
animacion = function(i){
$('#page2txt'+i).animate({
height:'20'
},200,function(){
$('#page2img'+i).animate({
left:'0',
right:'0'
},200,function(){
if(i < 3){
animacion(++i);
}
});
});
};
animacion(i);
};
Edit as you feel fit or post some markup to explain further.
Cheers.
来源:https://stackoverflow.com/questions/11555611/jquery-settimeout-while-loop