在jQuery库中,几乎所有的插件都被限制在它的命名空间里。通常,全局(global)对象都被很好地存储在jQuery命名空间里,一起jQuery和其他JS库一起使用时,不会引起冲突。
1、jQuery库在其他JS库之后导入
<script src="js/prototype.js"></script><script src="js/jQuery.js"></script>
默认情况下,jQuery用$作为自己的快捷方式。
在其他库和jQuery库都被加载完毕后,可以在任何时候调用jQuery.noConflict()函数来将变量$的控制权移交给其他JS库。
a、将jQuery()函数作为jQuery对象的制造工厂。
<script>jQuery.noConflict(); //将变量$的控制权移交给prototype.jsjQuery(function(){ //使用jQueryjQuery('p').click(funciton(){alert(jQuery(this).text() );});});$('p').style.display = 'none'; //使用prototype
</script>
b、不产生冲突,同时自定义快捷方式
<script>var $j = jQuery.noConflict(); //将变量$的控制权移交给prototype.js$j(function(){ //使用jQuery$j('p').click(funciton(){alert($j(this).text() );});});$('p').style.display = 'none'; //使用prototype</script>
c、不产生冲突,还要继续使用$,两种方法:
<script>jQuery.noConflict(); //将变量$的控制权移交给prototype.jsjQuery(function($){ //使用jQuery$('p').click(funciton(){alert($(this).text() );});});$('p').style.display = 'none'; //使用prototype</script>
<script>jQuery.noConflict(); //将变量$的控制权移交给prototype.js(function($){ //使用jQuery$('p').click(funciton(){alert($(this).text() );});})(jQuery);$('p').style.display = 'none'; //使用prototype</script>
*这是最理想的方式,可以通过改变最少的代码实现兼容性。
2、jQuery在其他库之前导入
<script src="js/jQuery.js"></script><script src="js/prototype.js"></script> 如果jQuery库在其他库之前就导入了,那么可以直接使用”jQuery“来做一些jQuery的工作。同时,可以使用$()方法作为其他库的快捷方式。这里无需调用jQuery.noConflict()函数。
<script>jQuery(function(){ //使用jQueryjQuery('p').click(funciton(){alert(jQuery(this).text() );});});$('p').style.display = 'none'; //使用prototype
</script>
<script>$(function(){ //使用jQuery$('p').click(funciton(){alert($(this).text() );});});$('p').style.display = 'none'; //使用prototype</script>
<script>jQuery(function($){ //使用jQuery$('p').click(funciton(){alert($(this).text() );});});$('p').style.display = 'none'; //使用prototype</script>
<script>(function($){ //使用jQuery$('p').click(funciton(){alert($(this).text() );});})(jQuery);$('p').style.display = 'none'; //使用prototype</script>