如何让 jQuery load() 在 fadeOut/fadeIn 之前完成?
我想通过 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用回调来控制调用的顺序。
(注意:我不是 100% 确定是否使用
var $data = ...
和$data.doStuff( )
实际上会起作用 - 如果可以的话,它可以让你不必每次都在 DOM 树中查找 div,但如果没有,只需删除第一行并使用$('#data')
到处...Use callbacks to the control the order of the calls.
(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...该问题与以下事实有关:fadeOut、load 和 fadeIn 这三个函数都是异步的。上述每个函数都接受一个回调参数(函数),该参数将在函数完成执行时运行。例如
//如果您定义了 'functionToRunWhenFadeOutIsComplete' 它将在 fadeOut 结束后运行。
有了这些知识,您现在就可以解决您的问题了。
或者,您可以将 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.
//If you have defined 'functionToRunWhenFadeOutIsComplete' it will run after fadeOut is over.
Armed with this knowledge, you can now solve your problem.
Alternatively, you can define loadData, fadeInData as an inline anonymous functions.