When developing with jQuery, you may also use other JS libraries, such as Prototype, but conflicts may occur when multiple libraries coexist. This article mainly introduces you to the perfect solution to jQuery library conflicts. What you need Friends can refer to it, let’s take a look below.
My idea is that if I are asked to design, then I will use a default value of $, and if no parameters are passed, then use $, and finally mount it on window.$, and pass in the parameters. Name, such as jq, then I will mount it on window.jq.
var myControl="jq"; (function(name){ var $=name ||"$"; //name存在$的值就是name的值,不存在或为null,$的值为字符串"$" console.log($); window[$]=function(){ alert("123"); } })(myControl) window[myControl]();
In fact, this is definitely not jquery’s way to resolve conflicts. Then take a look at how jQuery resolves conflicts.
Multiple versions of jQuery or conflicts with other js libraries are mainly conflicts with the commonly used $ symbol.
1. Conflict resolution
1. Conflict resolution of multiple versions of jQuery on the same page
<!-- 引入1.6.4版的jq --> <script></script> <script> var jq164 = jQuery.noConflict(true); </script> <!-- 引入1.4.2版的jq --> <script></script> <script> var jq142 = jQuery.noConflict(true); </script> <script> (function($){ //此时的$是jQuery-1.6.4 $('#'); })(jq164); </script> <script> jq142(function($){ //此时的$是jQuery-1.4.2 $('#'); }); </script>
2. Import the jQuery library after other libraries
jQuery noConflict() method releases control of the $ identifier so that other scripts can use it.
1. You can use jQuery by replacing its abbreviation with its full name.
After other libraries and the jQuery library are loaded, you can call the jQuery.noConflict() function at any time to Control of the variable $ is transferred to other JavaScript libraries. Then you can use the jQuery() function as a manufacturing factory for jQuery objects in your program.
<script></script> <script></script> <p>test---prototype</p> <p>test---jQuery</p> <script> jQuery.noConflict(); //将变量$的控制权让渡给prototype.js,全名可以不调用。 jQuery(function(){ //使用jQuery jQuery("p").click(function(){ alert( jQuery(this).text() ); }); }); //此处不可以再写成$,此时的$代表prototype.js中定义的$符号。 $("pp").style.display = 'none'; //使用prototype </script>
2. Customize a shortcut
noConflict() can return a reference to jQuery, which can be stored in a custom name, such as jq, $J variables, for later use use.
This ensures that jQuery will not conflict with other libraries, while using a customized shortcut.
<script> var $j = jQuery.noConflict(); //自定义一个比较短快捷方式 $j(function(){ //使用jQuery $j("p").click(function(){ alert( $j(this).text() ); }); }); $("pp").style.display = 'none'; //使用prototype </script>
3. If there is no conflict, still use $
If you want to use the $ abbreviation in the jQuery code block and are unwilling to change this shortcut, you can pass the $ symbol as a variable to ready method. In this way, you can use the $ symbol inside the function, but outside the function, you still have to use "jQuery".
<script> jQuery.noConflict(); //将变量$的控制权让渡给prototype.js jQuery(document).ready(function($){ $("p").click(function(){ //继续使用 $ 方法 alert( $(this).text() ); }); }); //或者如下 jQuery(function($){ //使用jQuery $("p").click(function(){ //继续使用 $ 方法 alert( $(this).text() ); }); }); </script>
Or use IEF statement blocks, which should be the most ideal way, because full compatibility can be achieved by changing the least code.
When we write our own jquery plug-ins, we should all use this way of writing, because we don’t know how to sequentially introduce various js libraries during the specific work process, but this way of writing statement blocks can shield conflicts. .
<script> jQuery.noConflict(); //将变量$的控制权让渡给prototype.js (function($){ //定义匿名函数并设置形参为$ $(function(){ //匿名函数内部的$均为jQuery $("p").click(function(){ //继续使用 $ 方法 alert($(this).text()); }); }); })(jQuery); //执行匿名函数且传递实参jQuery $("pp").style.display = 'none'; //使用prototype </script>
3. The jQuery library is imported before other libraries.
The jQuery library is imported before other libraries. The ownership of $ belongs to the following JavaScript library by default. Then you can use "jQuery" directly to do some jQuery work.
At the same time, you can use the $() method as a shortcut to other libraries. There is no need to call the jQuery.noConflict() function here.
<!-- 引入 jQuery --> <script></script> <!-- 引入 prototype --> <script></script> <p>Test-prototype(将被隐藏)</p> <p>Test-jQuery(将被绑定单击事件)</p> <script> jQuery(function(){ //直接使用 jQuery ,没有必要调用"jQuery.noConflict()"函数。 jQuery("p").click(function(){ alert( jQuery(this).text() ); }); }); $("pp").style.display = 'none'; //使用prototype </script>
2. Principle
1. Source code
Source code: Take a look at how to do it in the source code
var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; } });
In jQuery When loading, the current window.jQuery is obtained through the _jQuery variable declared in advance, and the current window.$ is obtained through _$.
Mount noConflict to jQuery through jQuery.extend(). So we always adjust jQuery.noConflict() like this when calling.
Made two judgments when calling noConflict(),
The first if, hands over the control of $.
The second if, hands over control of jQuery when noConflict() passes parameters.
Finally noConflict() returns the jQuery object, which parameter is used to receive it, and which parameter will have jQuery control.
2. Verification
//冲突 var $ = 123; //假设其他库中$为123 $( function () { console.log($); //报错Uncaught TypeError: $ is not a function } );
Resolve conflicts
//解决冲突 var jq = $.noConflict(); var $ = 123; jq(function () { alert($); //123 });
Release $control example
<script> var $ = 123; // window.$是123,存储在私有的_$上。 </script> <script></script> <p>aaa</p> <script> var jq = $.noConflict();//当window.$===jQuery的时候,把_$赋给了window.$。 jq(function () { alert($); //123 }); </script>
Release jQuery control example
The role of parameter deep: deep is used to abandon jQuery’s external interface.
As shown below, noConflict() does not write parameters and pops up jQuery as the constructor.
<script> var $ = 123; var jQuery=456; </script> <script></script> <p>aaa</p> <script> var jq = $.noConflict(); jq(function () { alert(jQuery); //构造函数 }); </script>
If you write a parameter true, 456 will pop up.
<script> var $ = 123; var jQuery=456; </script> <script></script> <p>aaa</p> <script> var jq = $.noConflict(true); //写了true或者参数的时候,deep为真window.jQuery===jQuery为真,所以进入if条件。把456赋值给window.jQuery jq(function () { alert(jQuery); //456 }); </script>
Related recommendations:
Use jquery.noConflict() to solve the problem of conflicts between jquery library and other libraries
How to write a js /jQuery library (summary of experience)
Solution to the conflict between jQuery library and other JS libraries_jquery
The above is the detailed content of What to do about jQuery library conflicts. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools

Atom editor mac version download
The most popular open source editor