8

jQuery での $(function(){ }) の呼び出しは、定義された順序で実行されることは知っていますが、キューの順序を制御できるかどうか疑問に思っています。

たとえば、「He​​llo World 1」の前に「Hello World 2」を呼び出すことは可能ですか?

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

問題はそれが可能かどうかです...私はそれがベストプラクティスに反することをすでに知っています;)

4

4 に答える 4

7

これを行う方法は次のとおりです。

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

詳細については、こちらをご覧ください。

于 2010-08-13T18:59:43.440 に答える
3

これらの関数はプライベート配列readyListに追加されるため、操作にはアクセスできません。

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

于 2010-08-13T18:40:50.733 に答える
2

jQuery promise を使用して、このようなことを実現できます。

以下は、jQuery.ready.promise が DOM Ready Blocks の実行順序の管理に役立つ例です。

  1. 次の例では、最初の DOM Ready ブロックが、後の DOM Ready ブロックで body に追加されるテスト 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 を使用する前の例とまったく同じことを行っています。Fiddle と同様に、必要に応じて機能します。

    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/

于 2013-04-30T10:56:33.623 に答える
1

それは可能ですが、簡単ではありません。おそらくここで、jQuery自体をハックする必要があります。jQuery がwhileループ内でこれらの関数の呼び出しを開始する前に、コードを追加してreadyList配列を検査し、好みに応じて要素を並べ替える必要があります。

于 2010-08-13T18:52:52.287 に答える