如何避免jquery库和其它库的冲突
来源:互联网 发布:2016好听的网络红歌 编辑:程序博客网 时间:2024/04/30 03:05
<span style="font-family: Verdana, Arial, Helvetica, sans-serif; line-height: 20.7999992370605px; background-color: rgb(255, 255, 255);">1.产生原因:</span>
默认情况下:jQuery使用 $ 作为jquery的快捷方式,如果别的js库也使用$的话,就可能产生冲突。为避免这种冲突,需要在把jquery引入页面后,使用jquery前把jquery设置为非冲突模式。
2.解决方法:
JQuery库在其他库之后导入——
方法1:使用jquery的命名空间,当然就不会冲突了。
<!-- Loading jQuery before other libraries --><script src="jquery.js"></script><script src="prototype.js"></script><script> <span style="white-space:pre"></span>JQuery.noConflict(); // Use full jQuery function name to reference jQuery jQuery(document).ready(function(){ jQuery("div").hide(); }); // Use the $ variable as defined in prototype.js window.onload = function() { var mainDiv = $('main'); }; </script>方法2:声明一个新的变量,来代替$。
<!-- Putting jQuery into no-conflict mode --><script src="prototype.js"></script><script src="jquery.js"></script><script> // $j is now an alias to the jQuery function; // creating the new alias is optional var $j = jQuery.noConflict(); $j(document).ready(function(){ $j("div").hide(); }); // The $ variable now has the prototype meaning, // which is a shortcut for document.getElementById. // mainDiv below is a DOM element, not a jQuery object window.onload = function(){ var mainDiv = $('main'); }</script>
如果不想给JQquery自定义这些备用名称,还想使用$而不管其他库的$()方法,同时又不想与其他库冲突,那么可以使用一下两种解决方法。
方法3:给ready()方法增加一个参数。比较常用此方法。
<!-- Another way to put jQuery into no-conflict mode --><script src="prototype.js"></script><script src="jquery.js"></script><script> jQuery.noConflict(); jQuery(document).ready(function($){ // You can use the locally-scoped $ in here as an alias to jQuery $("div").hide(); }); // The $ variable in the global scope has the prototype.js meaning window.onload = function(){ var mainDiv = $('main'); } </script>
方法4:
JQuery.noConflict();(function($){ (function($){ $("p").click(function(){ alert("$(this).text()); }) })})(JQuery);$("pp").style.display='none';JQuery库在其他库之前导入——
<script src="../JQuery/jquery.js" type="text/javascript"></script><script src="../lib/prototype.js" type="text/javascript"></script>有了这些方法解决冲突,就可以在项目中放心的引用JQuery了。
0 0
- 如何避免jquery库和其它库的冲突
- 如何避免jquery库和其它库的冲突
- jQuery 中 $ 避免跟其它库冲突
- 解决jQuery和其它库的冲突
- 解决jQuery和其它库的冲突
- jquery和其它js库起冲突的解决方法
- jQuery入门:避免和其他库冲突
- 锋利的jQuery学习笔记(二)—————解决jQuery和其它库的冲突
- jQuery避免$符和其他JS冲突的方法对比
- 解决jquery和其他库的冲突
- jQuery和其他库的冲突
- 解决jQuery和其他库的冲突
- 解决jQuery和其他库的冲突
- 解决jQuery和其他库的冲突
- 解决jQuery和其他库的冲突
- 解决jQuery和其他库的冲突
- 解决jquery和其他库的冲突
- 解决jQuery和其他库的冲突
- 命令 与 bash shell脚本
- ArcEngine加载天地图问题解决
- Canvas.clipRect(int left, int top, int right, int bottom)使用
- Android 进程间通信实现原理分析
- iOS优化项之开启Bitcode
- 如何避免jquery库和其它库的冲突
- redis安装以及php的redis扩展
- 【AcJoy群赛题解】 群赛02
- CString、CStringA 和 CStringW
- C# 获取本机“设备管理器”信息列表
- eclipse 远程调试 remote debug
- kafka java 实现消息队列demo
- 利用了相对坐标解决了商城项目开发中的一个问题。
- openlayer常见问题