我该如何初始化jQuery? [英] How should I initialize jQuery?
问题描述
我已经看过了(我也在使用它):
I have seen this (I'm also using it):
$(document).ready(function(){
// do jQuery
})
还有这个(我有)最近尝试过):
and also this (I have tried lately):
(function(){
// do jQuery
})(jQuery)
一切正常。
什么是这两者的区别(除了看起来如何)?
What is the difference of the two (except on how it looks)?
哪一个更合适?
推荐答案
第一个示例在构建DOM树时运行该函数。
第二个例子立即运行该函数。
The first example runs the function when the DOM tree is built. The second example runs the function right away.
如果仔细观察,在第二个例子中,函数声明后有两个括号(在此特定中)例如,您传入全局 jQuery
对象作为参数以避免冲突),从而立即调用函数
If you look closely, in the second example, there are two parentheses after the function declaration ( in this particular case, you pass in the global jQuery
object as an argument to avoid conflict ), thereby immediately invoking the function
正确使用的功能取决于您希望函数运行的时间。
如果你想在 DOMReady
( ready
事件)上运行一个函数,你可以使用 $(document).ready
就像你提到的那样或简写 $(function(){...})
。
The right function to use depends on when you want the function to run.
If you want to run a function on DOMReady
( the ready
event ), you can use $( document ).ready
like you mentioned or the shorthand $( function() {...} )
.
否则,如果要立即运行函数并具有匿名函数作用域,请使用第二个示例。
Otherwise, if you want to run a function immediately and have anonymous function scope, use the second example.
这篇关于我该如何初始化jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!