2014-03-19 28 views
0

I'm使用功能,将动画一些事情,例如:如何从函数返回,如果多个动画完成

function doMyStuff(){ 
$('#test1').animate({...}, {queue:false}); 
$('#test2').animate({...}, {queue:false}); 
return true; 
} 
// this should only go on if doMyStuff() is complete 
doMyStuff(); 
alert("We can go on, doMyStuff() is finished"); 

我只想去,如果此功能被完成了他动画。我怎样才能做到这一点?目前它并没有等待动画的结束。

回答

4

利用promises

function doMyStuff(){ 
    return $.when(
    $('#test1').animate({...}, {queue:false}).promise(), 
    $('#test2').animate({...}, {queue:false}).promise() 
    ); 
} 

doMyStuff().then(function() { 
    alert("We can go on, doMyStuff() is finished"); 
}); 

所有你想要执行完成动画必须从传递给.then回调后调用的代码。

.promise documentation(重点煤矿):

.promise()方法返回一个动态生成Promise是解决一旦某种类型绑定到集合中的所有动作,排队与否,已经结束。

缺省情况下,类型为"fx",这意味着当所选元素的所有动画完成返回Promise得到解决。

$.when只是简单地创建一个新的承诺,当所有的承诺传递给它的时候解决。

+0

现在我想知道为什么这个工作不使用'.promise()'?我的意思是:'return $ .when( $('#test1')。animate({...},{queue:false}), $('#test2')。animate({...} {queue:false}) );' –

+0

AFAIK,'$ .when'调用'.promise()'如果一个jQuery对象作为参数传递。但我喜欢明确:) –

+0

噢,只是检查jQuery源代码,好像是这样,thx! –