JavaScript中解决jQuery和Prototype.js同时引入冲突问题(示例代码)
1.同时引用jQuery和prototype
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 这里同时引用jQuery和prototype -->
<script src="https://cdn.staticfile.org/jquery/1.8.3/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/prototype/1.7.3/prototype.min.js"></script>
</head>
解决方法一
在引入jQuery后使用jQuery.noConflict();
返还$
使用权,否则Prototype.js会调用失败。
如何调用
- 在需要使用jQuery时,使用
jQuery( )
代替$( )
- 在需要使用Prototype.js时,使用
$( )
解决方法二
在引入jQuery后将jQuery的$
绑定到其他对象上,例如$j
,使用var $j = jQuery.noConflict();
。
如何调用
- 在需要使用jQuery时,使用
$j( )
代替$( )
- 在需要使用Prototype.js时,使用
$( )
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 7 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 <title>Document</title> 9 <!-- 这里同时引用jQuery和prototype --> 10 <script src="https://cdn.staticfile.org/jquery/1.8.3/jquery.min.js"></script> 11 <script src="https://cdn.staticfile.org/prototype/1.7.3/prototype.min.js"></script> 12 </head> 13 14 <body> 15 <!-- 正常js写法 --> 16 <p id="h01"></p> 17 <script> 18 function myFunction1() { 19 var obj = document.getElementById("h01"); 20 obj.innerHTML = "Hello js"; 21 } 22 onload = myFunction1; 23 </script> 24 25 <!-- 引用jQuery库写法 --> 26 <p id="h02"></p> 27 <script> 28 function myFunction2() { 29 //把$()改为jQuery() 30 jQuery("#h02").html("hello jQuery"); 31 } 32 jQuery(document).ready(myFunction2); 33 </script> 34 35 <!-- 引用prototype库写法 --> 36 <p id="h03"></p> 37 <script> 38 function myFunction3() { 39 $("h03").insert("Hello Prototype!"); 40 } 41 Event.observe(window, "load", myFunction3); 42 </script> 43 </body> 44 45 </html>
hello world!!!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步