您也可以嘗試使用隊列功能。
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後,
且不說它已經創造了位,程式精密的額外的好處整個執行序列定義它需要之前運行,使執行大部分是線性的。
因此,這使得代碼仍然是「你怎麼想它的工作原理」,並使它仍然運行「你需要它的工作方式」,而不必擔心它的全部不同步性。 (這使得更少的越野車和更可維護的代碼)