不同版本 jQuery 同时引用冲突怎么解决? 下面本篇文章给大家介绍一下. 有一定的参考价值, 有需要的朋友可以参考一下, 希望对大家有所帮助.
jQuery 的版本是不断提高的, 当前使用的版本不可能是最新的.
如果想在未来在现在 jQuery 代码的基础上添加新的功能, 并且使用新的 jQuery 版本库, 那么难免会出现冲突的情况.
jQuery 多个版本或和其他 JS 库冲突主要是常用的 $ 符号的问题, 这个问题 jQuery 早早就有给我们预留处理方法了, 下面一起来看看解决办法.
1, 同一页面 jQuery 多个版本或冲突解决方法.
- <!DOCTYPE html>
- <HTML>
- <head>
- <meta charset="utf-8" />
- <title>
- jQuery 测试页
- </title>
- </head>
- <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>
- </HTML>
2, 同一页面 jQuery 和其他 JS 库冲突解决方法
jQuery noConflict() 方法
noConflict() 方法会释放会 $ 标识符的控制, 这样其他脚本就可以使用它了.
jQuery.JS 在 prototype.JS 之前进行引入, 如:
- <script src="jquery.js" type="text/javascript">
- </script>
- <script src="prototype.js" type="text/javascript">
- </script>
- <p id="pp">
- test---prototype
- </p>
- <p>
- test---jQuery
- </p>
2.1 当然, 您仍然可以通过全名替代简写的方式来使用 jQuery:
<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>
2.2 您也可以创建自己的简写. noConflict() 可返回对 jQuery 的引用, 您可以把它存入变量, 以供稍后使用. 请看这个例子:
<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>
2.3 如果你的 jQuery 代码块使用 简写, 并且您不愿意改变这个快捷方式, 那么您可以把简写, 并且您不愿意改变这个快捷方式, 那么您可以把 符号作为变量传递给 ready 方法. 这样就可以在函数内使用 $ 符号了 - 而在函数外, 依旧不得不使用 "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>
2.4 使用语句块:
<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>
这种使用语句块的方法非常有用, 在我们自己写 jQuery 插件时, 应该都使用这种写法, 因为我们不知道具体工作过程中是如何顺序引入各种 JS 库的, 而这种语句块的写法却能屏蔽冲突.
注意:
引用 JavaScript 类库时, 把 jQuery 引用放在最后面, 可以避免冲突.
特别要注意 jQuery() 代替 $() 时, jQuery 是区分大小写的, 因为 JavaScript 本身就是区分大小写的.
更多 web 前端 https://www.html.cn/ 知识, 请查阅 HTML 中文网 !!
来源: http://www.css88.com/qa/jquery/17550.html