您也可以尝试使用队列功能。
http://docs.jquery.com/Effects/queue#callback
国内我还记得动画使用相同的执行队列,所以这在理论上应(未经测试)工作。
/* Safe Namespace + Onload : I do this everywhere */
jQuery(function($){
/* Calling this once instead of many times will save
a lot of wasted calls to document.getElementById + processing garbage
*/
var blerg = $('#blerg');
var addStep = function(i)
{
blerg.queue(function(){
console.log(i);
$(this).dequeue();
});
blerg.animate({top:'+=50px'},75,'linear');
/* In theory, this works like the callback does */
blerg.queue(function(){
log('animated');
$(this).dequeue();
});
};
for (var i=0;i<3;i++)
{
/* I call a function here, because that way you don't need to worry
about the fact 'i' will reference the last value of 'i' when the code
gets around to executing. */
addStep(i);
}
});
肯特,我不明白为什么你需要明确提出回调的 队列。不是你错了 - 如果回调是 animate()的一个参数,它就不起作用 - 但我只是好奇。
它不是必需的第二种情况,但我认为它更一致的,有点整洁代码所做的如果是要努力做更多的事情在回调阶段(例如,另一个动画)。
然后你只想把下一个动画调用中的第二blerg.queue后,
且不说它已经创造了位,程式精密的额外的好处整个执行序列定义它需要之前运行,使执行大部分是线性的。
因此,这使得代码仍然是“你怎么想它的工作原理”,并使它仍然运行“你需要它的工作方式”,而不必担心它的全部不同步性。 (这使得更少的越野车和更可维护的代码)