jQuery 不同形式的 $(document).ready
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1388043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Different forms of $(document).ready
提问by hobbs
I have seen people writing
我见过有人写
$(document).ready(function(){
});
and some writing
和一些写作
$(function() {
});
What's the difference and when to use what?
有什么区别以及何时使用什么?
回答by hobbs
$
is the jQuery object itself, which when called implements a whole pile of different interfaces. $('string')
runs a selector or constructs a node; $(domElement)
wraps an element... and $(a_function)
is a convenient short hand for $(document).ready(a_function)
. See the jQuery API docsfor (much) more information.
$
是 jQuery 对象本身,它在被调用时实现了一大堆不同的接口。$('string')
运行一个选择器或构造一个节点;$(domElement)
包装一个元素...并且$(a_function)
是 . 的方便简写$(document).ready(a_function)
。有关(更多)更多信息,请参阅jQuery API 文档。
A note in passing: $(function () { ... })
is shorter, but if you ever want to search for all of your on-ready events, you might be wishing that you had .ready
to search for :)
在路过的说明:$(function () { ... })
是短的,但如果你想搜索所有的准备的活动,你可能会希望你有.ready
寻找:)
回答by Aron Rotteveel
There is no difference.
没有区别。
One is a convenient shorthand that calls the other internally.
一个是方便的速记,可以在内部调用另一个。
From the jQuery docs:
来自jQuery 文档:
A shorthand for
$(document).ready()
. Allows you to bind a function to be executed when the DOM document has finished loading. This function behaves just like$(document).ready()
, in that it should be used to wrap other$()
operations on your page that depend on the DOM being ready to be operated on. While this function is, technically, chainable - there really isn't much use for chaining against it.You can have as many
$(document).ready
events on your page as you like. See ready(Function) for details about the ready event.
的简写
$(document).ready()
。允许您绑定要在 DOM 文档加载完成后执行的函数。这个函数的行为就像$(document).ready()
,因为它应该用于包装$()
页面上的其他操作,这些操作依赖于准备好操作的 DOM。虽然从技术上讲,这个函数是可链接的 - 链接它确实没有多大用处。您可以根据需要
$(document).ready
在页面上设置任意数量的事件。有关就绪事件的详细信息,请参阅 ready(Function)。