前四种,条件:jQuery库在其它库之后导入
在其它库和jQuery库都被加载完毕后,可以在任何时候调用jQuery.noConflict()函数来将变量$的控制权移交给其它JavaScript库。示例如下:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>冲突解决1</title> <!-- 引入 prototype --> <script src="prototype-1.6.0.3.js" type="text/javascript"></script> <!-- 引入 jQuery --> <script src="http://www.cnblogs.com/scripts/jquery-1.3.1.js" type="text/javascript"></script> </head> <body> <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() ); }); }); $("pp").style.display = 'none'; //使用prototype </script> </body> </html>
然后,就可以在程序里将jQuery ()函数作为jQuery对象的制造工厂。
此外,还有另一种选择。如果想确保jQuery不会与其它库冲突,但又想自定义一个比较短快捷方式,可以按照如下操作:
//...省略其他代码... var $j = jQuery.noConflict(); //自定义一个比较短快捷方式 $j(function(){ //使用jQuery $j("p").click(function(){ alert( $j(this).text() ); }); }); $("pp").style.display = 'none'; //使用prototype //...省略其他代码...
可以自定义备用名称,例如jq、$J、awesomequery--任何你想要的名称都行。
如果不想给jQuery自定义这些备用名称,还是想使用$而不管其它库的$方法,同时又不想与其它库相冲突,那么可以使用如下两种解决方法:
其一:
//...省略其他代码... jQuery.noConflict(); //将变量$的控制权让渡给prototype.js jQuery(function($){ //使用jQuery $("p").click(function(){ //继续使用 $ 方法 alert( $(this).text() ); }); }); $("pp").style.display = 'none'; //使用prototype //...省略其他代码...
其二:
//...省略其他代码... jQuery.noConflict(); //将变量$的控制权让渡给prototype.js (function($){ //定义匿名函数并设置形参为$ $(function(){ //匿名函数内部的$均为jQuery $("p").click(function(){ //继续使用 $ 方法 alert($(this).text()); }); }); })(jQuery); //执行匿名函数且传递实参jQuery $("pp").style.display = 'none'; //使用prototype //...省略其他代码...
对于大部分代码而言,这应该是最理想的方式,因为可以通过改变最少的代码来实现全面的兼容性。
2. jQuery库在其它库之前导入
如果jQuery库在其它库之前就导入了,那么可以直接使用"jQuery"来做一些jQuery的工作。同时,可以使用"$"方法作为其它库的快捷方式。
这里没有必要调用jQuery.noConflict()函数。
示例如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>冲突解决5</title> <!--先导入jQuery --> <script src="http://www.cnblogs.com/scripts/jquery-1.3.1.js" type="text/javascript"></script> <!--后导入其他库 --> <script src="prototype-1.6.0.3.js" type="text/javascript"></script> </head> <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> </html>

浙公网安备 33010602011771号