等待每个jQuery [英] wait for each jQuery
问题描述
我试图在每个语句中使div淡入/淡出.问题在于淡入/淡出完成之前会调用下一个项目.
I'm trying to make a div fade in/out that's within an each statement. The problem is that next item is called before the fade in/out is complete.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>
<div id='one'>one</div>
<div id='two'>two</div>
<div id='three'>three</div>
<script>
$.each([ "one", "two", "three"], function() {
console.log( 'start - ' + this );
animate( this );
console.log( 'end - ' + this );
});
function animate( id )
{
box = '#' + id;
$(box).fadeOut( 500, function( )
{
console.log('showing - ' + id);
$(box).fadeIn( 500 );
$(box).css('backgroundColor','white');
});
}
</script>
控制台显示-
start - one
end - one
start - two
end - two
start - three
end - three
showing - one
showing - two
showing - three
我想要类似-
start - one
showing - one
end - one
start - two
showing - two
end - two
start - three
showing - three
end - three
那么在继续下一个值之前,我该如何等待每个'b'完全完成 ?
So how can I wait for each 'each' to be completely finished before moving on to the next value?
推荐答案
您将不得不使用回调-当当前函数完成时将执行的函数.要使用.fadeOut
执行此操作,您可以执行以下操作:
Your going to have to use callbacks - functions that get executed when the current function is finished. To do this with .fadeOut
you would do:
$('#element').fadeOut( 400, myFunction );
myFunction直到fadeOut完成才被调用.带有$ .get的AJAX调用也可以具有回调函数.
myFunction would not be called until fadeOut was completed. AJAX calls with $.get also can have callback functions.
这是一个可行的示例,尽管我确信有更好的方法:
Here's an example that works, although I'm sure there's a better way:
function animate(myArray, start_index) {
// Stealing this line from Sam, who posted below.
if(!start_index) start_index = 0;
next_index = start_index+1;
if(next_index > myArray.length) { return; }
box = '#' + myArray[start_index];
$(box).fadeOut(500, function() { animate(myArray,next_index); });
}
,然后在您的文档中.您将调用:
and then in your document.ready you'd call:
animate(theArray);
这篇关于等待每个jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!