【发布时间】:2012-06-05 09:27:40
【问题描述】:
两者有什么区别:
$(document).ready(function() {// Do something});
和
$(function() {//Do something});
在 jQuery 中?
【问题讨论】:
标签: jquery
两者有什么区别:
$(document).ready(function() {// Do something});
和
$(function() {//Do something});
在 jQuery 中?
【问题讨论】:
标签: jquery
如果我简而言之,它们是别名。它们是等价的。
$(document).ready(function() {
})
$().ready(function() {
// this is not recommended
})
$(function() {
});
都是一样的。
jQuery 开发者推荐使用:
$(document).ready(function() {
});
为什么$().ready()不推荐看Why "$().ready(handler)" is not recommended?
【讨论】:
$(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;
},
【讨论】:
没有。
来自 jQ API:
以下三种语法都是等价的:
$(document).ready(handler) $().ready(handler) (this is not recommended) $(handler)
【讨论】:
它们是相同的(意味着它们做同样的事情)。检查文档中的这些行
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(处理程序。
【讨论】: