jQuery学习笔记2——解决与其他js框架冲突
jQuery学习笔记1——引入jQuery框架已经介绍了如果引入jQuery这一优秀js框架,但有时候处于项目的需要,要引入的js框架不止jQuery一个,这就可能造成框架间发生冲突。下面假如还需要引入Prototype框架来说明一下如何解决jQuery与其他框架间的冲突。
情况一:在其他框架之后引入jQuery
<!-- 引入 prototype --> <script src="lib/prototype.js" type="text/javascript"></script> <!-- 引入 jQuery --> <script src="lib/jquery-1.3.2.min.js" type="text/javascript"></script>
这种情况下,我们可以利用jQuery.noConflict()方法来移交变量$的控制权,并用jQuery变量来访问jQuery对象,如下:
<script type="text/javascript">
jQuery.noConflict();//移交变量$控制权给prototype
jQuery(function(){//使用jQuery变量访问jQuery对象
jQuery("#test-jq").click(function(){
alert(jQuery(this).text());
});
});
$("test-p").style.display = "none"; //使用变量$访问prototype
</script>
如果觉得用jQuery变量访问jQuery对象书写比较麻烦,那你完全可以自定义一个快捷变量,如:$j、jQ等等:
<script type="text/javascript">
var $j = jQuery.noConflict();//移交变量$控制权给prototype,并赋予$j
$j(function(){//使用jQuery变量访问jQuery对象
$j("#test-jq").click(function(){
alert($j(this).text());
});
});
$("test-p").style.display = "none"; //使用变量$访问prototype
</script>
假如你已经习惯了用$访问jQuery对象,不希望改变这种访问方式,同时又希望Prototype也可以使用$,那么在移交控制权之后,你可以用jQuery(function($){});把你要访问的方法包起来,然后在其内容使用$访问jQuery对象,有如下两种方式:
方式1:
<script type="text/javascript">
jQuery.noConflict();//移交变量$控制权给prototype
jQuery(function($){
$("#test-jq").click(function(){//在内部使用$
alert$(this).text());
});
});
$("test-p").style.display = "none"; //使用变量$访问prototype
</script>
方式2:
<script type="text/javascript">
jQuery.noConflict();//移交变量$控制权给prototype
(function($){
$(function(){//定义匿名函数
$("#test-jq").click(function(){//匿名函数中的$均为jQuery
alert$(this).text());
});
});
})(jQuery);//执行匿名函数并传递实参jQuery
$("test-p").style.display = "none"; //使用变量$访问prototype
</script>
方式2也是插件开发中常用的方式。
情况二:在其他框架之前引入jQuery
//之前代码省略...
<!--先导入jQuery -->
<script src="lib/jquery-1.3.2.min.js" type="text/javascript"></script>
<!--后导入其他库 -->
<script src="lib/prototype.js" type="text/javascript"></script>
//中间代码省略...
<script type="text/javascript">
jQuery(function(){//直接使用jQuery ,无需调用jQuery.noConflict()函数
jQuery("#test-jq").click(function(){
alert(jQuery(this).text());
});
});
$("test-p").style.display = "none"; //使用变量$访问prototype
</script>
OK,现在你可以放心结合其他js框架使用jQuery了,笔记2到此结束,( ^_^ )/~~拜拜