finding last loop through a jQuery object
Sample jquery. Assume $cog is a cached selector of multiple items.
$cog.fadeOut('slow',function(){
alert('hey');
})
In that example, of $cog is a jQuery object of 4 DOM elements, the above wil开发者_Go百科l fade each element out one by one, and trigger an alert each time on the callback (4 alerts).
I'd like to only call the alert when all 4 elements are done with their fadeOut function.
This:
$cog.fadeOut('slow',function(){
})
alert('hey');
when run, will show an alert, then the $cog elements disappear (I'm guessing due to timing issues with the fadeOut animation)
Is there a way when calling a function against multiple DOM objects in a jQuery object to know when it's done with the last item?
You can simply count the callbacks back in.
Try this:
var remaining=$cog.length;
$cog.fadeOut('slow',function(){
if((--remaining)==0)alert('hey');
})
Try this example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var items = $("li");
$("#btn").click(function() {
(function() {
var items = $("li");
items.fadeOut("slow", function() {
items = items.not(this);
console.log(items.length);
if (items.length == 0) {
alert("all done");
}
});
})();
});
});
</script>
<style type="text/css">
</style>
</head>
<body>
<input type="button" id="btn" value="Fade Out">
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
</body>
</html>
精彩评论