【问题标题】:How to wait until a jQuery animation has finished before calling next functions?如何在调用下一个函数之前等到 jQuery 动画完成?
【发布时间】:2013-01-24 17:34:01
【问题描述】:

在调用下一个函数之前,我无法完成我的 jquery 函数。

基本上,我试图让我的新闻文章淡出,并在通过 ajax 检索下一页文章之前完成所有淡出动画。

这就是我所拥有的(抽样以仅包括相关功能)。

控制每篇新闻文章淡出的功能...

function fadeArticlesOut() {
    var delay = 0;
    //set timeout for image to appear (set at 500ms)
    $('#news-articles article').each(function(index) {
        $(this).delay(delay).fadeTo(800, 0);
        delay += 400;       
    })
};          

通过点击分页链接触发的功能。这将捕获要通过 ajax 加载的 url,但在此之前,这是我要运行淡出功能的地方,即 fadeArticlesOut。我想要的是在运行 loadProducts 函数之前完成淡出动画。

function doPager() {
    $('.pagination-controls a').click(function(e) {
        e.preventDefault();

        fadeArticlesOut();          
        loadProducts($(this).attr('href'));
        history.pushState(null, null, $(this).attr('href'));
        historyedited = true;
    });
}

function loadProducts(url) {
    $('#news-articles').empty().addClass('loading').load(url + ' #news-articles-inner', function() {
        $('#news-articles').removeClass('loading');
        doPager();
        fadeArticlesIn();
    });
}

一旦完成,加载产品功能将在新的新闻文章中消失。

到目前为止,我已经尝试了许多方法,包括使用自定义回调、延迟对象和设置超时。我遇到的问题是我可以让它运行淡出,然后不继续加载 ajax 内容,或者没有淡出,但获取 ajax 内容。

【问题讨论】:

  • 查看延迟对象/Promise 对象。你可以在你的 fadeTo() 调用之后添加一个 .done() 函数处理程序,它会在淡入淡出完成时触发。

标签: jquery


【解决方案1】:

您可以通过使用.promise() 获得承诺,然后添加.done() 处理程序。

function fadeArticlesOut() {
    ...
    return $('#news-articles article').each(function(index) {
      ...
    }).promise();
};  

function doPager() {
    $('.pagination-controls a').click(function(e) {
        var $self = $(this);
        ...
        fadeArticlesOut().done(function(){
            loadProducts($self.attr('href'));
        });          
        ...
    });
}

.done() 处理程序将在所有动画完成后被调用。

【讨论】:

  • 绝对完美,谢谢。我曾尝试过 promise/done 组合,但错过了将 $(this) 的使用更改为 $self = $(this);在我的 doPager 函数中。完美解决了我的问题,再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-01
  • 2017-03-15
  • 2014-01-24
  • 2022-11-03
  • 2016-11-29
  • 2021-05-25
  • 1970-01-01
相关资源
最近更新 更多