完了関数またはコールバックがネストされすぎたり、コードが何度も繰り返されたりする場合は、共通の関数を使用したデータテーブルソリューションについて考える傾向があります。
function fadeSequence(list) {
var index = 0;
function next() {
if (index < list.length) {
$(list[index++]).fadeOut(next);
}
next();
}
var fades = ["div1", "div2", "div3", "div4", "div5"];
fadeSequence(fades);
また、一部のアイテムに異なるタイプのアニメーションが必要な場合は、連続する各アニメーションがどうあるべきかを説明するオブジェクトの配列を作成できます。オブジェクトの配列には、必要なだけ詳細を入れることができます。次のように、アニメーションを他の同期jQueryメソッド呼び出しと混合することもできます。
function runSequence(list) {
var index = 0;
function next() {
var item, obj, args;
if (index < list.length) {
item = list[index++];
obj = $(item.sel);
args = item.args.slice(0);
if (item.sync) {
obj[item.type].apply(obj, args);
setTimeout(next, 1);
} else {
args.push(next);
obj[item.type].apply(obj, args);
}
}
}
next();
}
// sequence of animation commands to run, one after the other
var commands = [
{sel: "#div2", type: "animate", args: [{ width: 300}, 1000]},
{sel: "#div2", type: "animate", args: [{ width: 25}, 1000]},
{sel: "#div2", type: "fadeOut", args: ["slow"]},
{sel: "#div3", type: "animate", args: [{ height: 300}, 1000]},
{sel: "#div3", type: "animate", args: [{ height: 25}, 1000]},
{sel: "#div3", type: "fadeOut", args: ["slow"]},
{sel: "#div4", type: "fadeOut", args: ["slow"]},
{sel: "#div1", type: "fadeOut", args: ["slow"]},
{sel: "#div5", type: "css", args: ["position", "absolute"], sync: true},
{sel: "#div5", type: "animate", args: [{ top: 500}, 1000]}
];
runSequence(commands);
そして、これがこの2番目のオプションの実用的なデモです:http://jsfiddle.net/jfriend00/PEVEh/