How to get jQuery to wait until an effect is finished?

I am sure I read about this the other day but I can't seem to find it anywhere.
I have a fadeOut() event after which I remove the element, but jQuery is removing the element before it has the chance to finish fading out.
How do I get jQuery to wait until the element had faded out, then remove it?

176860 次浏览

您可以指定一个回调函数:

$(selector).fadeOut('slow', function() {
// will be called when the element finishes fading out
// if selector matches multiple elements it will be called once for each
});

文件在此

如果你想切换,淡出一个和淡出另一个在同一个地方,你可以在 div 上放置一个{ position: Absol}属性,这样两个动画就可以一个接一个地播放,你不必等到一个动画结束后才开始下一个动画。

在 jQuery 1.6版本中,可以使用 .promise()方法。

$(selector).fadeOut('slow');
$(selector).promise().done(function(){
// will be called when all the animations on the queue finish
});

你也可以使用 $.when()来等待,直到 promise完成:

var myEvent = function() {
$( selector ).fadeOut( 'fast' );
};
$.when( myEvent() ).done( function() {
console.log( 'Task finished.' );
} );

如果你正在做一个可能会失败的请求,那么你甚至可以更进一步:

$.when( myEvent() )
.done( function( d ) {
console.log( d, 'Task done.' );
} )
.fail( function( err ) {
console.log( err, 'Task failed.' );
} )
// Runs always
.then( function( data, textStatus, jqXHR ) {
console.log( jqXHR.status, textStatus, 'Status 200/"OK"?' );
} );