推迟行动直到 .each() 完成

Deferring action until .each() has completed

我有以下方法:

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

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

这可以通过 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 
    });

可以使用动画返回的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>

不要将 done 与动画承诺一起使用,就好像任何处于目标状态的人都不会开火。使用 always() 代替

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