Home Web Front-end JS Tutorial What to do about jQuery library conflicts

What to do about jQuery library conflicts

Jan 11, 2018 pm 02:08 PM
jquery conflict what to do

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]();
Copy after login

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

<body>
<!-- 引入1.6.4版的jq -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>
<script> var jq164 = jQuery.noConflict(true); </script>
<!-- 引入1.4.2版的jq -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script> var jq142 = jQuery.noConflict(true); </script>

<script>
(function($){
 //此时的$是jQuery-1.6.4
 $('#');
})(jq164);
</script>
 
<script>
jq142(function($){
 //此时的$是jQuery-1.4.2
 $('#');
});
</script>
 
</body>
Copy after login

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 src="prototype.js" type="text/javascript"></script>
<script src="jquery.js" type="text/javascript"></script>

<p id="pp">test---prototype</p>
<p>test---jQuery</p>

<script type="text/javascript">
jQuery.noConflict();  //将变量$的控制权让渡给prototype.js,全名可以不调用。
jQuery(function(){   //使用jQuery
 jQuery("p").click(function(){
 alert( jQuery(this).text() );
 });
});
//此处不可以再写成$,此时的$代表prototype.js中定义的$符号。

$("pp").style.display = 'none'; //使用prototype
</script>
Copy after login

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 type="text/javascript">
var $j = jQuery.noConflict(); //自定义一个比较短快捷方式
$j(function(){   //使用jQuery
 $j("p").click(function(){
 alert( $j(this).text() );
 });
});

$("pp").style.display = 'none'; //使用prototype
</script>
Copy after login

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 type="text/javascript">
jQuery.noConflict(); //将变量$的控制权让渡给prototype.js
jQuery(document).ready(function($){
 $("p").click(function(){ //继续使用 $ 方法
 alert( $(this).text() );
 });
});
//或者如下
jQuery(function($){   //使用jQuery
 $("p").click(function(){ //继续使用 $ 方法
 alert( $(this).text() );
 });
});
</script>
Copy after login

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 type="text/javascript">
jQuery.noConflict();  //将变量$的控制权让渡给prototype.js
(function($){   //定义匿名函数并设置形参为$
 $(function(){   //匿名函数内部的$均为jQuery
 $("p").click(function(){ //继续使用 $ 方法
  alert($(this).text());
 });
 });
})(jQuery);    //执行匿名函数且传递实参jQuery

$("pp").style.display = 'none'; //使用prototype
</script>
Copy after login

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 src="../../scripts/jquery.js" type="text/javascript"></script>
<!-- 引入 prototype -->
<script src="lib/prototype.js" type="text/javascript"></script>

<body>
<p id="pp">Test-prototype(将被隐藏)</p>
<p >Test-jQuery(将被绑定单击事件)</p>

<script type="text/javascript">
jQuery(function(){ //直接使用 jQuery ,没有必要调用"jQuery.noConflict()"函数。
 jQuery("p").click(function(){  
  alert( jQuery(this).text() );
 });
});

$("pp").style.display = 'none'; //使用prototype
</script>
</body>
Copy after login

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;
  }
});
Copy after login

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
   }
 );
Copy after login

Resolve conflicts

//解决冲突
 var jq = $.noConflict();
 var $ = 123;
 jq(function () {
  alert($); //123
 });
Copy after login

Release $control example

<script>
 var $ = 123; // window.$是123,存储在私有的_$上。

</script>
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<body>
<p>aaa</p>
<script>
 var jq = $.noConflict();//当window.$===jQuery的时候,把_$赋给了window.$。
 jq(function () {
  alert($); //123
 });
</script>
Copy after login

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 src="https://code.jquery.com/jquery-2.0.3.js"></script>
<body>
<p>aaa</p>
<script>
 var jq = $.noConflict();
 jq(function () {
  alert(jQuery); //构造函数
 });
</script>
Copy after login


If you write a parameter true, 456 will pop up.

<script>
 var $ = 123;
 var jQuery=456;
</script>
<script src="https://code.jquery.com/jquery-2.0.3.js"></script>
<body>
<p>aaa</p>
<script>
 var jq = $.noConflict(true); //写了true或者参数的时候,deep为真window.jQuery===jQuery为真,所以进入if条件。把456赋值给window.jQuery
 jq(function () {
  alert(jQuery); //456
 });
</script>
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I forget my Ouyi Wallet mnemonic phrase? Can it still be found? What should I do if I forget my Ouyi Wallet mnemonic phrase? Can it still be found? Jul 19, 2024 pm 12:13 PM

In the Web3 world, although it is free, it is full of dangers. Therefore, the first step in the security of Ouyi wallet is to protect the private key and mnemonic phrase. Everyone knows the importance of private keys, and today the emphasis is on mnemonics. The mnemonic phrase can be understood as another form of presentation of the private key. Having the mnemonic phrase is equivalent to owning the private key and controlling the wallet assets. It is also thought that its presence is lower than that of the private key, and users may forget the mnemonic phrase of Ouyi Wallet. So what should I do if I forget the mnemonic phrase of Ouyi Wallet? Can I still retrieve my Ouyi Wallet mnemonic if I forget it? Issues that users need to pay attention to. Generally speaking, if the mnemonic phrase is forgotten, it cannot be retrieved, but try to contact the relevant customer service personnel for help. The editor below will tell you in detail. What should I do if I forget my Ouyi Wallet mnemonic phrase? If you forget the mnemonic phrase of Ouyi Wallet, please try to recall it or contact us.

Solve the problem of being unable to access the Internet even though the broadband is connected (troubleshooting) Solve the problem of being unable to access the Internet even though the broadband is connected (troubleshooting) May 05, 2024 pm 06:01 PM

The Internet has become an indispensable part of people's lives in today's information age. But we can't get online, and sometimes we encounter some troubles. However, for example, the broadband is already connected. And take corresponding solution measures, we need to troubleshoot the problem step by step to restore the network connection in this case. Confirm the device connection status: Whether the mobile phone and other devices have been correctly connected to the broadband network, check the computer to ensure that the wireless network or wired network connection is normal. 2. Restart the broadband device: Reset the device and re-establish the connection, wait a few minutes and then turn it back on again. Try turning off the broadband router or modem. 3. Check the broadband account number and password: To avoid being unable to access the Internet due to incorrect account or password, make sure the broadband account number and password entered are correct. 4. Check D

What to do if snowflakes appear on your TV (A practical way to solve the problem of snowflakes on your TV) What to do if snowflakes appear on your TV (A practical way to solve the problem of snowflakes on your TV) Jun 01, 2024 pm 09:44 PM

In our daily lives, TV, as an important entertainment device, often suffers from snowflakes, which affects our viewing experience. This article will introduce you to practical methods to solve the TV snow problem and help you enjoy TV programs better. 1. Analysis of the causes of snowflake problems Snowflakes appearing on TVs are generally caused by signal interference, antenna problems or TV signal sources. 2. Check whether the antenna connection is loose. First, check whether the connection between the TV and the antenna is firm. If it is loose, plug it in again. 3. Choose a suitable antenna to ensure that the position and direction of the antenna are correct. Choosing an antenna with good performance can improve the signal reception quality. 4. Adjust the direction of the antenna. Find the best signal reception direction by rotating or adjusting the angle of the antenna. 5. Use indoor antenna signals

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to solve the rustling sound during TV playback (eliminate TV rustling sound) How to solve the rustling sound during TV playback (eliminate TV rustling sound) Jul 21, 2024 pm 03:29 PM

With the advancement of technology and people's increasing demand for high-definition picture quality, TV has become an indispensable part of home entertainment. However, sometimes you may hear an annoying rustling sound while watching TV, which not only affects the viewing experience, but may also cause the TV to malfunction. This article will introduce some methods to solve the rustling sound during TV playback, so that you can enjoy a higher quality movie viewing experience. 1: Check whether the audio cable connection is loose. If there is a rustling sound when the TV is playing, first check whether the audio cable connection is firm. Make sure both ends of the audio cable are plugged into the correct connectors and check for loose connections or poor connections. Two: Adjust the TV volume and audio device settings. Appropriately adjusting the TV volume and audio device settings will help eliminate rustling sounds. try

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

The computer does not have Bluetooth, how to solve it (how to quickly add Bluetooth function and precautions) The computer does not have Bluetooth, how to solve it (how to quickly add Bluetooth function and precautions) Jun 29, 2024 pm 06:57 PM

In modern society, Bluetooth has become an indispensable technology in our daily lives. However, for some older computers, they may not have built-in Bluetooth functionality. What if your computer does not have Bluetooth and you want to use a Bluetooth device? This article will introduce you to several methods and precautions for quickly adding Bluetooth functionality. 1. Use a Bluetooth adapter - A Bluetooth adapter is an external device that can be connected to a computer through a USB interface. -Purchase a compatible Bluetooth adapter and install the driver according to the instructions. -Plug the Bluetooth adapter into the USB port of your computer and wait for the system to automatically install the driver. 2. Check the driver 1. Check if there is a Bluetooth device on the computer. Open the device manager and check if there is a Bluetooth device. if not

See all articles