我们在项目中除了JQuery 有可能要用到其他的JavaScript 库(Ext.js, prototype)时,有可能会与原来的JQuery 库冲突,下面记录了几个解决方法,供大家参考,mark一下
方法一 自定义快捷方式
(1) 使用JQuery作为调用 JQuery的快捷方式
<script> jQuery.noConflict(); jQuery(function(){ var $test = jQuery('#test'); //jQuery获取元素内容 console.log("第一种冲突解决方法 "+$test.html()); //javaScript获取元素内容 var dom = $test.get(0); for(var i = 0; i<dom.childNodes.length; i++){ if(dom.childNodes[i].nodeType == 3){ console.log(dom.childNodes[i].nodeValue); } } }); </script>
(2)使用自定义的符号作为快捷方式
<script> var $j = jQuery.noConflict(); $j(function(){ //jQuery获取元素内容 console.log("第二种冲突解决方法 "+$j('#test').html()); }); </script>
方法二 在函数内部使用JQuery方法
(1)
<script> jQuery.noConflict(); jQuery(function($){ //jQuery获取元素内容 console.log("第三种冲突解决方法 "+$('#test').html()); }); </script>
(2)
<script> jQuery.noConflict(); (function($){ $(function(){ //jQuery获取元素内容 console.log("第四种冲突解决方法 "+$('#test').html()); }); })(jQuery); </script>
整体测试代码:
<meta charset="UTF-8" /> <title></title> <script src="js/jquery-1.11.3.js"></script><script> jQuery.noConflict(); jQuery(function(){ var $test = jQuery('#test'); //jQuery获取元素内容 console.log("第一种冲突解决方法 "+$test.html()); //javaScript获取元素内容 var dom = $test.get(0); for(var i = 0; i<dom.childNodes.length; i++){ if(dom.childNodes[i].nodeType == 3){ console.log(dom.childNodes[i].nodeValue); } } }); </script>
<script> var $j = jQuery.noConflict(); $j(function(){ //jQuery获取元素内容 console.log("第二种冲突解决方法 "+$j('#test').html()); }); </script><script> jQuery.noConflict(); jQuery(function($){ //jQuery获取元素内容 console.log("第三种冲突解决方法 "+$('#test').html()); }); </script><script> jQuery.noConflict(); (function($){ $(function(){ //jQuery获取元素内容 console.log("第四种冲突解决方法 "+$('#test').html()); }); })(jQuery); </script>