jQuery,在多个动画之后仅调用一次回调 [英] jQuery, calling a callback only once after multiple animations
问题描述
假设我一次运行了多个动画,并且我想在所有动画完成后调用一个函数.
Let's say that I have several animations running at once, and I want to call a function once all of them are finished.
只有一个动画,这很容易;有一个回调.例如:
With only one animation, it's easy; there's a callback for that. For example :
$(".myclass").fadeOut(slow,mycallback);
麻烦的是,如果我的选择器找到多个项目,则将为每个项目调用回调.
Trouble is, if my selector finds several items, the callback will be called for each of them.
一种解决方法不是太难;例如:
A workaround is not too hard; for example :
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var $mc=$(".myclass"),l=$mc.length;
$mc.fadeOut("slow",function(){
if (! --l) $("#target").append("<p>All done.</p>");
});
});
</script>
<style type="text/css">
</style>
</head>
<body>
<p class="myclass">Paragraph</p>
<p class="myclass">Paragraph</p>
<p class="myclass">Paragraph</p>
<p class="myclass">Paragraph</p>
<p class="myclass">Paragraph</p>
<p class="myclass">Paragraph</p>
<div id="target"></div>
</body>
</html>
我的问题是:有更好的方法吗?
My question is : is there a better way to do this ?
推荐答案
Look at the discussion on this thread: jQuery $.animate() multiple elements but only fire callback once
.when()/.then()
和.promise().done(callback());
函数为在所有动画结束时调用单个回调的问题提供了一种更为优雅的解决方案.
The .when()/.then()
and the .promise().done(callback());
functions provide a much more elegant solution to the problem of calling a single calllback at the end of all animations.
这篇关于jQuery,在多个动画之后仅调用一次回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!