jQuery中$(document).ready(…)和$(function(){})之间有什么区别?
有什么区别:
$(document).ready(function() {// Do something});
和
$(function() {//Do something});
在jQuery?
$(document).ready(handler) $().ready(handler) (this is not recommended) $(handler)
是等价的。
实际上,你可以在任何 jQuery对象上调用.ready(handler)
,无论它包含什么,它都会做同样的事情:
ready: function( fn ) { // Attach the listeners jQuery.bindReady(); // Add the callback readyList.add( fn ); return this; },
如果我简单地尝试,那么它们就是别名 。 它们是等价的。
注意
$(document).ready(function() { }) $().ready(function() { // this is not recommended }) $(function() { });
一切都一样。
更多
jQuery开发人员建议使用:
$(document).ready(function() { });
为什么$().ready()
不建议参见为什么不建议使用“$()。ready(handler)”?
没有。
来自jQ API:
以下所有三种语法都是等效的:
$(document).ready(handler) $().ready(handler) (this is not recommended) $(handler)
它们是相同的(意味着它们做同样的事情)。 从doc查看这些行
All three of the following syntaxes are equivalent: $(document).ready(handler) $().ready(handler) (this is not recommended) $(handler)
实际上$(handler)
是$(document).ready(handler)
的硬编码快捷方式。 在这里的源代码http://code.jquery.com/jquery.js如果你搜索rootjQuery
你很快就会发现这些行
// HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); }
或者点击此链接https://github.com/jquery/jquery/blob/37ffb29d37129293523bf1deacf3609a28b0ceec/src/core.js#L174查找
意味着如果传递的selector
是一个函数,那么它被用作$(document).ready(
handler。
还要检查哪个JQuery document.ready更好?