如何让 jQuery load() 在 fadeOut/fadeIn 之前完成?

发布于 2024-08-07 06:52:20 字数 234 浏览 1 评论 0原文

我想通过 jQuery load() 进行 AJAX 调用,并且只有在返回后,才会淡出旧内容并淡入新内容。我希望旧内容保持显示,直到检索到新内容,此时触发淡出/淡入。

使用:

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

内容淡入和淡出,稍后 load() 调用返回,并且数据更新,但淡入淡出已经完成。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

如痴如狂 2024-08-14 06:52:20

使用回调来控制调用的顺序。

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

(注意:我不是 100% 确定是否使用 var $data = ... $data.doStuff( ) 实际上会起作用 - 如果可以的话,它可以让你不必每次都在 DOM 树中查找 div,但如果没有,只需删除第一行并使用 $('#data') 到处...

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...

↙温凉少女 2024-08-14 06:52:20

该问题与以下事实有关:fadeOut、load 和 fadeIn 这三个函数都是异步的。上述每个函数都接受一个回调参数(函数),该参数将在函数完成执行时运行。例如

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

//如果您定义了 'functionToRunWhenFadeOutIsComplete' 它将在 fadeOut 结束后运行。

有了这些知识,您现在就可以解决您的问题了。

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

或者,您可以将 loadData、fadeInData 定义为内联匿名函数。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文