jQuery中的队列是什么? [英] What are queues in jQuery?

查看:79
本文介绍了jQuery中的队列是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现queue()/dequeue()上的jQuery.com文档太简单了. jQuery中的队列到底是什么?我应该如何使用它们?

I found the jQuery.com document on queue()/dequeue() is too simple to understand. What exactly are queues in jQuery? How should I use them?

推荐答案

jQuery的使用 .queue() .dequeue()

jQuery中的

队列用于动画.您可以将它们用于任何您喜欢的目的.它们是使用每个 jQuery.data() .它们是先进先出(FIFO).您可以通过调用 .queue() 将函数添加到队列中,然后删除(通过调用)函数使用 .dequeue() .

The uses of jQuery .queue() and .dequeue()

Queues in jQuery are used for animations. You can use them for any purpose you like. They are an array of functions stored on a per element basis, using jQuery.data(). They are First-In-First-Out (FIFO). You can add a function to the queue by calling .queue(), and you remove (by calling) the functions using .dequeue().

要了解内部jQuery队列功能,请读取源代码查看示例可以极大地帮助我.我见过的队列功能的最佳示例之一是 .delay() :

To understand the internal jQuery queue functions, reading the source and looking at examples helps me out tremendously. One of the best examples of a queue function I've seen is .delay():

$.fn.delay = function( time, type ) {
  time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
  type = type || "fx";

  return this.queue( type, function() {
    var elem = this;
    setTimeout(function() {
      jQuery.dequeue( elem, type );
    }, time );
  });
};

默认队列-fx

jQuery中的默认队列是fx.默认队列具有一些与其他队列不共享的特殊属性.

The default queue - fx

The default queue in jQuery is fx. The default queue has some special properties that are not shared with other queues.

  1. 自动启动::调用$(elem).queue(function(){});时,fx队列将自动dequeue下一个函数并在队列未启动时运行它.
  2. 'inprogress'前哨:每当您从fx队列中dequeue()一个函数时,它将unshift()(推入数组的第一个位置)字符串"inprogress"-标记当前正在运行队列.
  3. 这是默认设置! .animate()队列由.animate()和所有默认调用它的函数使用.
  1. Auto Start: When calling $(elem).queue(function(){}); the fx queue will automatically dequeue the next function and run it if the queue hasn't started.
  2. 'inprogress' sentinel: Whenever you dequeue() a function from the fx queue, it will unshift() (push into the first location of the array) the string "inprogress" - which flags that the queue is currently being run.
  3. It's the default! The fx queue is used by .animate() and all functions that call it by default.

注意::如果您使用的是自定义队列,则必须手动.dequeue()这些功能,它们不会自动启动!

NOTE: If you are using a custom queue, you must manually .dequeue() the functions, they will not auto start!

您可以通过调用不带函数参数的.queue()来检索对jQuery队列的引用.如果要查看队列中有多少个项目,可以使用该方法.您可以使用pushpopunshiftshift来就地操纵队列.您可以通过将数组传递给.queue()函数来替换整个队列.

You can retrieve a reference to a jQuery queue by calling .queue() without a function argument. You can use the method if you want to see how many items are in the queue. You can use push, pop, unshift, shift to manipulate the queue in place. You can replace the entire queue by passing an array to the .queue() function.

快速示例:

// lets assume $elem is a jQuery object that points to some element we are animating.
var queue = $elem.queue();
// remove the last function from the animation queue.
var lastFunc = queue.pop(); 
// insert it at the beginning:    
queue.unshift(lastFunc);
// replace queue with the first three items in the queue
$elem.queue(queue.slice(0,3)); 

动画(fx)队列示例:

在jsFiddle上运行示例

An animation (fx) queue example:

Run example on jsFiddle

$(function() {
    // lets do something with google maps:
    var $map = $("#map_canvas");
    var myLatlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {zoom: 8, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
    var geocoder = new google.maps.Geocoder();
    var map = new google.maps.Map($map[0], myOptions);
    var resized = function() {
        // simple animation callback - let maps know we resized
        google.maps.event.trigger(map, 'resize');
    };

    // wait 2 seconds
    $map.delay(2000);
    // resize the div:
    $map.animate({
        width: 250,
        height: 250,
        marginLeft: 250,
        marginTop:250
    }, resized);
    // geocode something
    $map.queue(function(next) {
        // find stackoverflow's whois address:
      geocoder.geocode({'address': '55 Broadway New York NY 10006'},handleResponse);

      function handleResponse(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
              var location = results[0].geometry.location;
              map.setZoom(13);
              map.setCenter(location);
              new google.maps.Marker({ map: map, position: location });
          }
          // geocoder result returned, continue with animations:
          next();
      }
    });
    // after we find stack overflow, wait 3 more seconds
    $map.delay(3000);
    // and resize the map again
    $map.animate({
        width: 500,
        height: 500,
        marginLeft:0,
        marginTop: 0
    }, resized);
});

另一个自定义队列示例

在jsFiddle上运行示例

var theQueue = $({}); // jQuery on an empty object - a perfect queue holder

$.each([1,2,3],function(i, num) {
  // lets add some really simple functions to a queue:
  theQueue.queue('alerts', function(next) { 
    // show something, and if they hit "yes", run the next function.
    if (confirm('index:'+i+' = '+num+'\nRun the next function?')) {
      next();
    }
  }); 
});

// create a button to run the queue:
$("<button>", {
  text: 'Run Queue', 
  click: function() { 
    theQueue.dequeue('alerts'); 
  }
}).appendTo('body');

// create a button to show the length:
$("<button>", {
  text: 'Show Length', 
  click: function() { 
    alert(theQueue.queue('alerts').length); 
  }
}).appendTo('body');

排队Ajax调用:

我开发了一个 $.ajaxQueue() 插件,该插件使用 $.Deferred $.ajax() 也会传回<请求完成后解决的href ="http://api.jquery.com/Types/#Promise" rel ="noreferrer">承诺.在我对对Ajax请求进行排序

Queueing Ajax Calls:

I developed an $.ajaxQueue() plugin that uses the $.Deferred, .queue(), and $.ajax() to also pass back a promise that is resolved when the request completes. Another version of $.ajaxQueue that still works in 1.4 is posted on my answer to Sequencing Ajax Requests

/*
* jQuery.ajaxQueue - A queue for ajax requests
* 
* (c) 2011 Corey Frang
* Dual licensed under the MIT and GPL licenses.
*
* Requires jQuery 1.5+
*/ 
(function($) {

// jQuery on an empty object, we are going to use this as our Queue
var ajaxQueue = $({});

$.ajaxQueue = function( ajaxOpts ) {
    var jqXHR,
        dfd = $.Deferred(),
        promise = dfd.promise();

    // queue our ajax request
    ajaxQueue.queue( doRequest );

    // add the abort method
    promise.abort = function( statusText ) {

        // proxy abort to the jqXHR if it is active
        if ( jqXHR ) {
            return jqXHR.abort( statusText );
        }

        // if there wasn't already a jqXHR we need to remove from queue
        var queue = ajaxQueue.queue(),
            index = $.inArray( doRequest, queue );

        if ( index > -1 ) {
            queue.splice( index, 1 );
        }

        // and then reject the deferred
        dfd.rejectWith( ajaxOpts.context || ajaxOpts,
            [ promise, statusText, "" ] );

        return promise;
    };

    // run the actual query
    function doRequest( next ) {
        jqXHR = $.ajax( ajaxOpts )
            .done( dfd.resolve )
            .fail( dfd.reject )
            .then( next, next );
    }

    return promise;
};

})(jQuery);


我现在将此内容添加为学习的文章.jquery.com ,该网站上还有其他有关队列的精彩文章,请看看.


I have now added this as an article on learn.jquery.com, there are other great articles on that site about queues, go look.

这篇关于jQuery中的队列是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆