【问题标题】:Deferring action until .each() has completed推迟操作直到 .each() 完成
【发布时间】:2015-08-06 10:13:41
【问题描述】:

我有以下方法:

function animatePortfolio(fadeElement) {
    fadeElement.children('article').each(function(index) {
        $(this).delay(1000*index).fadeIn(900);
    });
}

我想推迟操作,直到 .each() 完全完成。假设这是我需要使用的某个版本的 deferred/promise,但不了解在这种情况下它将如何工作。

【问题讨论】:

  • 应该推迟什么操作
  • @ArunPJohny 在所有元素淡入后需要发生的另一个动画。
  • 正如我在下面所说的,不要将done 与动画承诺一起使用。请改用always。请参阅下面的答案。

标签: javascript jquery promise each jquery-deferred


【解决方案1】:

你可以使用动画返回的promise对象

function animatePortfolio(fadeElement) {
  fadeElement.children('article').each(function(index) {
    $(this).delay(1000 * index).fadeIn(900);
  }).promise().done(function() {
    fadeElement.css('color', 'red')
  });
}


animatePortfolio($('div'))
article {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <article>1</article>
  <article>2</article>
  <article>3</article>
  <article>4</article>
</div>

【讨论】:

  • 哦,这很好(等待元素而不是它的子元素)。
  • @Benjamin Gruenbaum:这是不正确的。它在等待子动画队列的集体承诺,而不是在父元素上。 (each 调用的返回值之前的children() 集合)
  • 成功了。我不明白.promise().done() 需要串联使用。
【解决方案2】:

这可以通过done函数来完成

function animatePortfolio(fadeElement) {
   fadeElement.children('article').each(function(index) {
      $(this).delay(1000*index).fadeIn(900);
  }).promise().done(function(){
     // do aditional animation here 
   });
 }

当函数被调用时在那里进行

    animatePortfolio(fadeElement).promise().done(function(){

     // do things here 
    });

【讨论】:

    【解决方案3】:

    不要将done 与动画承诺一起使用,就好像任何处于目标状态的东西一开始就不会触发。请改用always()

    function animatePortfolio(fadeElement) {
       fadeElement.children('article').each(function(index) {
          $(this).delay(1000*index).fadeIn(900);
      }).promise().always(function(){
         // do aditional animation here 
       });
     }
    

    【讨论】:

      猜你喜欢
      • 2021-03-20
      • 1970-01-01
      • 1970-01-01
      • 2019-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多