我知道 jQuery 中对 $(function(){ }) 的调用是按照定义的顺序执行的,但我想知道您是否可以控制队列的顺序?
例如,是否可以在“Hello World 1”之前调用“Hello World 2”:
$(function(){ alert('Hello World 1') });
$(function(){ alert('Hello World 2') });
问题是这是否可能......我已经知道这违背了最佳实践;)
您将按照以下方式进行操作:
// 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)