关于jquery自定义队列出队的混淆

时间:2012-06-27 00:47:30

标签: jquery queue

首先我有一个工厂函数来改变背景颜色,该函数正在推送一个自定义队列:

var changeBack = function (delay, color) {
    $('div').queue('custom', function (next) {
        setTimeout(function () {
            $('div').css({
                'background-color': color
            })
        }, delay)   
    })    
}

然后我想多次更改背景颜色,然后dequeue队列:

$(function () {
    changeBack(1000, "yellow");
    changeBack(1000, "black");
    changeBack(1000, "blue");
    changeBack(1000, "gray");
    var custom = $('div').queue('custom');
    $('div').dequeue('custom');
})

但是div只转向黄色背景颜色,这意味着只执行第一个函数?但是我已将其他函数推入队列,我该如何执行其他函数? 这是demo

1 个答案:

答案 0 :(得分:0)

正确的延迟方式不是setTimeout,而是$.fn.delayhttp://jsfiddle.net/uVjQ4/8/

var changeBack = function (delay, color) {
    var $div = $('div'); //<-- Cached selector, so that the selected element(s) 
                         // are same throughout the whole function.
    $div.delay(delay, 'custom').queue('custom', function (next) {
        ....
        next(); // Trigger next
    });
};

....
// Initialize 
    $('div').dequeue('custom');