代码之家  ›  专栏  ›  技术社区  ›  Derek Hunziker

jQuery多文档就绪队列顺序

  •  8
  • Derek Hunziker  · 技术社区  · 14 年前

    我知道jQuery中对$(function(){})的调用是按照定义的顺序执行的,但是我想知道您是否可以控制队列的顺序?

    例如,是否可以在“Hello World 1”之前调用“Hello World 2”:

    $(function(){ alert('Hello World 1') });
    $(function(){ alert('Hello World 2') });
    

    4 回复  |  直到 14 年前
        1
  •  3
  •   user113716    14 年前

    这些函数被添加到私有数组中 readyList ,所以我得说它是不可操作的。

    http://github.com/jquery/jquery/blob/master/src/core.js#L47

        2
  •  7
  •   ovais.tariq    14 年前

    // lower priority value means function should be called first
    var method_queue = new Array();
    
    method_queue.push({
      method : function()
      { 
        alert('Hello World 1');
      },
      priority : 2
    });
    
    method_queue.push({
      method : function()
      { 
        alert('Hello World 2');
      },
      priority : 1
    });
    
    
    function sort_queue(a, b)
    {
      if( a.priority < b.priority ) return -1;
      else if( a.priority == b.priority ) return 0;
      else return 1;  
    }
    
    function execute_queue()
    {
      method_queue.sort( sort_queue );
    
      for( var i in method_queue ) method_queue[i].call( null );
    }
    
    // now all you have to do is 
    execute_queue();
    

    你可以多看看 here

        3
  •  2
  •   GeekTantra    11 年前

    您可以使用jquerypromise来实现这样的功能。

    下面是一个例子jQuery.ready.promise命令帮助管理DOM就绪块的执行顺序:

    1. 在下面的示例中,第一个DOM就绪块尝试访问附加到后面DOM就绪块的主体的test div的高度。就像在小提琴中一样,它无法得到它。

      jQuery(function () {
          var testDivHeight = jQuery("#test-div").outerHeight();
          if(testDivHeight) {
              alert("Height of test div is: "+testDivHeight);
          } else {
              alert("Sorry I cannot get the height of test div!");
          }
      });
      jQuery(function () {
          jQuery('body').append('<div style="background: #C00; height: 100px;" id="test-div"></div>');
      });
      

      http://jsfiddle.net/geektantra/qSHec/

    2. 在下面的示例中,它的操作与使用之前的示例完全相同jQuery.ready.promise命令. 就像小提琴一样,它能按要求工作。

      jQuery(function () {
          jQuery.ready.promise().done(function () {
              var testDivHeight = jQuery("#test-div").outerHeight();
              if(testDivHeight) {
                  alert("Height of test div is: "+testDivHeight);
              } else {
                  alert("Sorry I cannot get the height of test div!");
              }
          });
      });
      jQuery(function () {
          jQuery('body').append('<div style="background: #C00; height: 100px;" id="test-div"></div>');
      });
      

      小提琴: http://jsfiddle.net/geektantra/48bRT/

        4
  •  1
  •   Ken Redler    14 年前

    可以做到,但不容易。你可能需要破解jQuery本身 here . 在jQuery开始在 while 循环,您必须添加代码来检查 readyList 根据您的喜好排列元素并重新排序。