wait for each jQuery

心不动则不痛 提交于 2019-12-01 03:51:29

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

Sounds like you are trying to "cycle" through a list of divs. Have you checked out the jQuery Cycle plugin?

How about this, animate by going through each items in the array within the function?

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

You can even loop back to the start if you want:

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');
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!