当我在没有任何参数的情况下调用jQuery集合上的promise
方法时,我得到一个承诺,一旦集合中元素的所有动画完成,它就会解决。对该元素的相同方法的每次进一步调用都将返回相同的承诺。是否有一种直接的方法来"重置"承诺,以便一旦初始动画完成并且初始承诺已经解决,我可以处理下一个动画完成时?
$('.some-element').slideDown();
$('.some-element').promise().done(function () {
// e.g. evaluate the "display" property of the element which should not be "none"
this.slideUp();
this.promise().done(function () {
// e.g. evaluate the "display" property of the element which should be "none"
});
});
上面代码中的问题是第二次调用promise
返回与第一次调用相同的承诺。由于这个承诺已经被解决了,第二个处理程序中的求值显示"display"属性不是"none",因为slideUp
动画尚未完成。
Try
$(function () {
function slider(d, next, callback) {
$("div").slideUp({
duration: d,
done: function (promise) {
if (promise.state() === "resolved"
&& $(this).css("display") === "none") {
console.log($(this).css("display"));
$(this).slideDown({
duration: d,
done: function (promise) {
if (promise.state() === "resolved"
&& $(this).css("display") === "block") {
console.log($(this).css("display"));
slider(next, (d + next) / 2, function () {
console.log("next animation beginning at "
+ $.now());
});
}
},
complete: function () {
return callback != undefined ? callback() : $.noop();
}
});
};
}
});
};
slider(3000, 1500, function () {
console.log("next animation beginning at " + $.now())
});
});
jsfiddle http://jsfiddle.net/guest271314/3xdmD/
参见http://api.jquery.com/slideup/, http://api.jquery.com/slidedown/options
at start
, progress
, done
, always
(promises
);参见step
, complete
回调
您可以将承诺数组传递给$.when
,如文档