简体   繁体   English

为什么(jQuery)在函数右括号后

[英]why is (jQuery) after function closing bracket

I'm working with a Magento site. 我正在使用Magento网站。 I'm running into an issue getting Magento's prototype.js to play nice with jQuery. 我遇到了使Magento的prototype.js与jQuery配合使用的问题。 I've read that all of my jQuery needs to be using jQuery.noConflict(); 我读过我所有的jQuery需要使用jQuery.noConflict();。 which I've done but am still having some issues. 我已经做了,但是仍然有一些问题。 I have seen that some functions closing brackets are followed by (jQuery). 我已经看到,一些函数在右括号后跟(jQuery)。

I'm wondering what this is for and if I need to change it to (jQuery.noConflict())? 我想知道这是什么意思,是否需要将其更改为(jQuery.noConflict())?

There is no need to change (jQuery) to (jQuery.noConflict()) as long as jQuery.noConflict() is called before that point (and after the JQuery library is included). 只要在该点之前(包括JQuery库之后jQuery.noConflict()调用jQuery.noConflict()就无需将(jQuery)更改为(jQuery.noConflict()) )。

As you know, when you are using jQuery in no-conflict mode, you should use jQuery instead of $ . 如您所知,当您在无冲突模式下使用jQuery ,应该使用jQuery而不是$

But you can use $ instead of jQuery in code placed inside an immediately invoked function expression (IIFE), like this: 但是您可以在放置在立即调用的函数表达式(IIFE)中的代码中使用$而不是jQuery ,如下所示:

(function($) {
    // Code here can use $, instead of jQuery.
})(jQuery);

An IIFE is where you define an anonymous function and immediately call it. IIFE是您定义匿名函数并立即调用它的地方。 In the code above, the jQuery object is passed as an argument to the anonymous function, and since the parameter is named $ , $ represents the jQuery object inside the function. 在上面的代码中, jQuery对象作为参数传递给匿名函数,并且由于参数名为$ ,因此$表示函数内部的jQuery对象。

Also, the jQuery object is passed as the first parameter to the callback function for the document-ready event, so you can do the following: 另外, jQuery对象作为第一个参数传递给文档就绪事件的回调函数,因此您可以执行以下操作:

jQuery(function($) {
    // Code here can use $, instead of jQuery.
});

Which is the same as: 与以下内容相同:

jQuery(document).ready(function($) {
    // Code here can use $, instead of jQuery.
});

Just be aware that variables declared with var inside an IIFE are not global. 请注意,在IIFE中用var声明的变量不是全局变量。 This is often a good thing, and is another reason to use IIFEs. 这通常是一件好事,并且是使用IIFE的另一个原因。 If you do want to declare a global variable inside an IIFE, you should refer to it as a property of the window object. 如果确实要在IIFE中声明全局变量,则应将其称为window对象的属性。

<script type="text/javascript">
var a = 1; // This is a global variable.
(function($) {
    var b = 2; // This is NOT a global variable.
    window.c = 3; // This is a global variable.
})(jQuery);
<script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM