解决jQuery和其他库的冲突---jQuery()与$()的区别

来源:互联网 发布:汉字 知乎 编辑:程序博客网 时间:2024/04/30 01:14

在jQuery库中,$就是jQuery的一个简写形式,例如$("#divId")和 jQuery("#divId")是等价的,$ajax和$jQuery.ajax是等价的,但是,

在引入jQuery库的同时也引入的其他js库,如prototype,都被加载完毕后,会出现用$(id)时出错,而用jQuery(id)就没问题

当jQuery库被引用在其他js库之后,就会出现上面的问题,解决方法:调用jQuery.noConflict()函数,将变量$的控制权移交给其他js库 ,这时,必须在以后的代码中使用jQuery来代替$

 

<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="../../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.jsjQuery(function(){//使用jQueryjQuery("p").click(function(){alert( jQuery(this).text() );});});$("pp").style.display = 'none';//使用prototype</script></body></html>


此外,第二种方法,如果想确保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 type="text/javascript">jQuery.noConflict();//将变量$的控制权让渡给prototype.jsjQuery(function($){//使用jQuery$("p").click(function(){//继续使用 $ 方法alert( $(this).text() );});});$("pp").style.display = 'none';//使用prototype

第四种:

<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库在其他库导入之前就导入了,那么可以直接使用jQuery来做一些jQuery的工作,同时使用$()做其他库的快捷方式,这里无需调用jQuery.noConflict()函数

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


 

 

原创粉丝点击