How can I get jQuery load() to complete before fadeOut/fadeIn?

拜拜、爱过 提交于 2019-12-20 02:13:01

问题


I want to do an AJAX call via jQuery load() and only once it returns, then fadeOut the old content and fadeIn the new content. I want to old content to remain showing until the new content is retrieved, at which point the fade Out/In is triggered.

Using:

$('#data').fadeOut('slow').load('/url/').fadeIn('slow');

the content fades in and out and a few moments the later the load() call returns, and the data updates, but the fade has already completed.


回答1:


Use callbacks to the control the order of the calls.

var $data = $('#data');
$data.fadeOut('slow', function() { 
    $data.load('/url/', function() { 
        $data.fadeIn('slow'); 
    }); 
});

(Note: I'm not 100% sure about if using var $data = ... and $data.doStuff() will actually work - if it does, it saves you from having to look up the div in the DOM tree every time, but if it doesn't, just remove the first line and use $('#data') everywhere...




回答2:


The problem is related to the fact that all three functions, fadeOut, load and fadeIn are asynchronous. Each of the above functions accept a callback argument (a function) which will run when the function has finished execution. E.g.

$('#data').fadeOut(functionToRunWhenFadeOutIsComplete);

//If you have defined 'functionToRunWhenFadeOutIsComplete' it will run after fadeOut is over.

Armed with this knowledge, you can now solve your problem.

var fadeInData = function fadeInData() { $('#data').fadeIn(); }
var loadData = function loadData() { $('#data').load('url', fadeInData); }
$('#data').fadeOut(loadData);

Alternatively, you can define loadData, fadeInData as an inline anonymous functions.



来源:https://stackoverflow.com/questions/1550642/how-can-i-get-jquery-load-to-complete-before-fadeout-fadein

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!