jQuery 如何让jQuery等待效果完成?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1065806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:33:12  来源:igfitidea点击:

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

jquery

提问by uriDium

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, thenremove it?

我确定我前几天读到过这个,但我似乎在任何地方都找不到。
我有一个fadeOut()事件,之后我删除了该元素,但是 jQuery 在它有机会完成淡出之前删除了该元素。
如何让 jQuery 等待元素淡出,然后将其删除?

回答by Reinaldo Junior

With jQuery 1.6 version you can use the .promise()method.

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

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

回答by Paolo Bergantino

You can specify a callback function:

您可以指定回调函数:

$(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
});

Documentation here.

文档在这里

回答by kaiser

You can as well use $.when()to wait until the promisefinished:

您也可以使用$.when()等待promise完成:

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

In case you're doing a request that could as well fail, then you can even go one step further:

如果您正在执行的请求也可能失败,那么您甚至可以更进一步:

$.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"?' );
    } );

回答by Samin

if its something you wish to switch, fading one out and fading another in the same place, you can place a {position:absolute} attribute on the divs, so both the animations play on top of one another, and you don't have to wait for one animation to be over before starting up the next.

如果你想切换某个东西,在同一个地方淡出另一个淡出,你可以在 div 上放置一个 {position:absolute} 属性,这样两个动画就会在另一个上面播放,而你没有在开始下一个动画之前等待一个动画结束。