开发者

jQuery - Queue unrelated DOM elements in the same queue

开发者 https://www.devze.com 2023-03-13 15:09 出处:网络
I\'ve been reading all types of examples about jQuery\'s queue() function, all of them demonstrate with only one DOM element.

I've been reading all types of examples about jQuery's queue() function, all of them demonstrate with only one DOM element.

What I need is to run an event on one element and once that's complete run an event on another element.

I've made up an example to test this: http://jsfiddle.net/paulmason411/4F6CE/

Basically I want the first block to fade, and then when that's finishe开发者_如何学God the second block fade. I got it working using the nested method, but it's commented out, and not the suitable method for me.

Any ideas? Is queue the right function for this? Thanks.


I used some of the concepts Liangliang Zheng shared and have come up with a simple solution:

http://jsfiddle.net/paulmason411/4F6CE/5/

Think it works quite well, let me know if you can see a way to trim it back at all, cheers!


I don't know about queue, but here's what I do when faced with a similar problem:

var elements = [$("#box-1"), $("#box-2"), $("#box-3"), $("#box-4")];

function fadeElement(el){
    elements[el].fadeOut(3000, function () {
        if(el < elements.length){
            fadeElement(el+1);
        }
    });
}

// call once to start the ball rolling
fadeElement(0);

To add more elements to it just add them to the array.

http://jsfiddle.net/4F6CE/2/ <-- jsfiddle - it works


I think this would be a decent solution to your case:

// if you more boxes, add to [1, 2]
$(document).queue('a', $.map([1, 2], function(val){
    return function(){$('#box-' + val).fadeOut(3000, 
        function(){$(document).dequeue('a')}) // call back
    };
}));

$(document).dequeue('a');

And I thought the following would be helpful to you

;(function(w){
w.Queue = function(){
    this.funcs = [];
    this._delay = 1000;
};
w.Queue.prototype = {
    add : function(func){
        this.funcs.push(func);
    }, 
    finalFunc: function(func){
        this._finalFunc = func;
    },
    run : function(){
        if(this.funcs.length > 0){
            var func = this.funcs.shift();
            func();
            var t = this;
            setTimeout(function(){t.run()}, this._delay);
        } else {
            if(typeof this._finalFunc == 'function')
                this._finalFunc();
        }
    }
}
})(window);

// your code from here

var q = new Queue();
q.add(function(){$('#box-1').fadeOut(3000)});
q.add(function(){$('#box-2').fadeOut(3000)});
q.run();
0

精彩评论

暂无评论...
验证码 换一张
取 消