等待每个jQuery

我试图让每个声明中的div淡入/淡出。 问题是在淡入/淡出完成之前调用下一个项目。

 
one
two
three
$.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'); }); }

控制台节目 –

 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 

那么在继续下一个值之前,我怎么能等待每个’每个’ 完全完成?

您将不得不使用回调 – 当前函数完成时执行的函数。 要使用.fadeOut执行此操作,您可以执行以下操作:

 $('#element').fadeOut( 400, myFunction ); 

在fadeOut完成之前,不会调用myFunction。 使用$ .get调用AJAX也可以有回调函数。

这是一个有效的例子,虽然我确信有更好的方法:

 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); }); } 

然后在你的document.ready你打电话:

 animate(theArray); 

听起来你正试图通过一系列div来“循环”。 你有没有看过jQuery Cycle插件 ?

怎么样,通过遍历函数中的数组中的每个项目来制作动画?

 var elements = [ "one", "two", "three"]; animate(elements); function animate( elements, index ) { if(!index) index = 0; var box = '#' + elements[index]; var $$box = $("#box"); console.log( 'start - ' + elements[index] ); $$box.fadeOut( 500, function( ) { console.log('showing - ' + elements[index]); $$box.fadeIn( 500, function() { console.log( 'end - ' + elements[index] ); if(elements[++index]) animate(elements, index); } ).css('backgroundColor','white'); }); } 

如果需要,您甚至可以循环回到开头:

 var elements = [ "one", "two", "three"]; animate(elements); function animate( elements, index ) { if(!index) index = 0; var box = '#' + elements[index]; var $$box = $(box); console.log( 'start - ' + elements[index] ); $$box.fadeOut( 500, function( ) { console.log('showing - ' + elements[index]); $$box.fadeIn( 500, function() { $$box.css('backgroundColor','white'); console.log( 'end - ' + elements[index] ); // go to next element, or first element if at end index = ++index % (elements.length); animate(elements, index); } ); }).css('backgroundColor', 'aqua'); }