jQuery函数语法差异 [英] jQuery Functions Syntax Difference
问题描述
如何:
(function($) {
/// code
})(jQuery)
与jquery中的$(document).ready(function()
有什么区别?
differ from $(document).ready(function()
in jquery?
我知道ready
函数的作用.它等待,直到HTML加载完毕才开始.但是,(function($)
会做同样的事情吗?
I know what the ready
function does. It awaits until the HTML is loaded before it starts. However, does (function($)
do the same?
推荐答案
$(document).ready()
的简写"就是$()
:
//both do the same thing
$(document).ready(function(){
//run when DOM is ready
});
$(function(){
//run when DOM is ready
});
但是,您的第一个代码与.ready()
相同.您所拥有的是一个 立即调用的函数表达式 (IIFE),或者用 layman的术语来说,立即运行此功能"
However, your first code is NOT the same as .ready()
. What you have there is an immediately-invoked function expression (IIFE), or in layman's terms, "run this function immediately"
//both are the same
(function($) {
//run stuff here immediately!
})(jQuery) //arguments outside wrapping parenthesis
(function($) {
//run stuff here immediately!
}(jQuery)) //arguments inside wrapping parenthesis
这等于函数和调用"之类的内容,但没有函数名称(匿名函数)和调用:
This is just equal to something like this "function-and-call" but without the function name (an anonymous function) and the call:
function functionWithNoName($){
//"jQuery" in the call is "$" in here
}
functionWithNoName(jQuery)
此方法通常用于保护使用$
用于jQuery的代码,而其他库使用相同的$
函数名称
this method is often used to protect code that uses $
for jQuery while other libraries are using the same $
function name, thus prevent conflicts. jQuery just uses $
for a shorthand alias to jQuery
(you would not want to type jQuery('selector')
all the time, $('selector')
is shorter)
(function($) {
//run jQuery using the "$" safely in here
}(jQuery))
//while some other libraries like mootools use "$" out here
这篇关于jQuery函数语法差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!