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>
复制代码

 

posted @   低调的小白  阅读(139)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示