jQuery 的 function($) (jQuery) 语法 [英] jQuery's function($) (jQuery) syntax

查看:27
本文介绍了jQuery 的 function($) (jQuery) 语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
jQuery:做什么 (function($) {})(jQuery);是什么意思?

我偶然发现了以下代码(包含在一个文件中),但我无法理解它的真正含义.

I stumbled up on the following code (included in one file) but I just cannot understand what it really means.

(function ($) {
    function doSomething1(somedata) {

    }

    function doSomething1(somedata) {

    }
})(jQuery);

问题 1:这个语法在 jQuery 的上下文中意味着什么

Question 1: What does this syntax mean in the contex of jQuery

问题 2:我们如何从其他文件(例如 HTML 索引文件和其他 JavaScript 文件)调用这些函数?

Question 2: How can we call these functions let say from other files such as the HTML index file and other JavaScript files?

谢谢

推荐答案

这种语法对于 jquery 来说并不是特别特殊,它是普通的 javascript.这里只是函数

This syntax is not particularly special to jquery, it's normal javascript. Here simply function

function ($) {
    // some code here...
}

(注意它需要名为 $ 的参数)使用参数 jQuery(显然,这是 jQuery 框架的全局对象)调用.

(note that it takes argument named $) is called with parameter jQuery (which is, obviously, global object of jQuery framework).

这通常是在一个页面上有多个 js 框架(jquery、dojo、prototype 等)都重新定义了全局变量 $ 时完成的.但是使用此代码,在 doSomething1doSomething2 中,您始终可以调用 $('.test') 并确保调用将由jquery,而不是 dojo.因为在这种情况下 $ 不是全局变量,它是函数参数.

This is usually done when there're several js frameworks on one page (jquery, dojo, prototype, etc) which all redefine global variable $. But with this code, inside doSomething1 or doSomething2 you can always call $('.test') and be certain that call will be processed by jquery, not dojo. Because $ is not a global variable in this case, it's function parameter.

这篇关于jQuery 的 function($) (jQuery) 语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆