如何避免jquery库和其它库的冲突
来源:互联网 发布:如何拍评价蛤蟆知乎 编辑:程序博客网 时间:2024/04/30 02:13
1.产生原因:
默认情况下:jQuery使用 $ 作为jquery的快捷方式,如果别的js库也使用$的话,就可能产生冲突。为避免这种冲突,需要在把jquery引入页面后,使用jquery前把jquery设置为非冲突模式。
2.解决方法:
方法1:使用jquery的命名空间,当然就不会冲突了。
1 <!-- Loading jQuery before other libraries --> 2 <script src="jquery.js"></script> 3 <script src="prototype.js"></script> 4 <script> 5 6 // Use full jQuery function name to reference jQuery 7 jQuery(document).ready(function(){ 8 jQuery("div").hide(); 9 });10 11 // Use the $ variable as defined in prototype.js12 window.onload = function() {13 var mainDiv = $('main');14 };15 16 </script>
方法2:声明一个新的变量,来代替$。
1 <!-- Putting jQuery into no-conflict mode --> 2 <script src="prototype.js"></script> 3 <script src="jquery.js"></script> 4 <script> 5 // $j is now an alias to the jQuery function; 6 // creating the new alias is optional 7 var $j = jQuery.noConflict(); 8 $j(document).ready(function(){ 9 $j("div").hide();10 });11 12 // The $ variable now has the prototype meaning,13 // which is a shortcut for document.getElementById.14 // mainDiv below is a DOM element, not a jQuery object15 window.onload = function(){16 var mainDiv = $('main');17 }18 </script>
方法3:给ready()方法增加一个参数。比较常用此方法。
1 <!-- Another way to put jQuery into no-conflict mode --> 2 <script src="prototype.js"></script> 3 <script src="jquery.js"></script> 4 <script> 5 6 jQuery.noConflict(); 7 jQuery(document).ready(function($){ 8 // You can use the locally-scoped $ in here as an alias to jQuery 9 $("div").hide();10 });11 12 // The $ variable in the global scope has the prototype.js meaning13 window.onload = function(){14 var mainDiv = $('main');15 }16 17 </script>
- 如何避免jquery库和其它库的冲突
- 如何避免jquery库和其它库的冲突
- jQuery 中 $ 避免跟其它库冲突
- 解决jQuery和其它库的冲突
- 解决jQuery和其它库的冲突
- jquery和其它js库起冲突的解决方法
- jQuery入门:避免和其他库冲突
- 锋利的jQuery学习笔记(二)—————解决jQuery和其它库的冲突
- jQuery避免$符和其他JS冲突的方法对比
- 解决jquery和其他库的冲突
- jQuery和其他库的冲突
- 解决jQuery和其他库的冲突
- 解决jQuery和其他库的冲突
- 解决jQuery和其他库的冲突
- 解决jQuery和其他库的冲突
- 解决jQuery和其他库的冲突
- 解决jquery和其他库的冲突
- 解决jQuery和其他库的冲突
- mina与spring集成(翻译)
- MINA与JMX集成(翻译)
- mina应用程序架构(翻译)
- mina 之IoService(翻译)
- jquery学习手记(1)
- 如何避免jquery库和其它库的冲突
- 九度笔记之 1337:寻找最长合法括号序列
- jquery学习手记(2)jQuery对象和DOM对象相互转换
- jquery学习手记(3)属性
- HDU ACM 1050 Moving Tables
- 程序员面试宝典节选 第9到12章 笔记
- jquery学习手记(4)元素的选择与操作
- jquery学习手记(5)对象
- jquery学习手记(6)CSS, Styling, & Dimensions