一,jQuery庫在其他庫之後導入
在其它庫和jQuery庫都被加載完畢後,可以在任何時候調用jQuery.noConflict()函數來将變量$的控制權移交給其它JavaScript庫。示例如下:
1. <html>
2. <head>
3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
4. <title>沖突解決1</title>
5. <!-- 引入 prototype -->
6. <script src="prototype-1.6.0.3.js" type="text/javascript"></script>
7. <!-- 引入 jQuery -->
8. <script src="../../scripts/jquery-1.3.1.js" type="text/javascript"></script>
9. </head>
10. <body>
11. <p id="pp">test---prototype</p>
12. <p >test---jQuery</p>
13.
14. <script type="text/javascript">
15. jQuery.noConflict();
16. jQuery(function(){ //使用jQuery
17. jQuery("p").click(function(){
18. alert( jQuery(this).text() );
19. });
20. });
21.
22. $("pp").style.display = 'none'; //使用prototype
23. </script>
24.
25. </body>
26. </html>
然後,就可以在程式裡将jQuery ()函數作為jQuery對象的制造工廠。
此外,還有另一種選擇。如果想確定jQuery不會與其它庫沖突,但又想自定義一個比較短快捷方式,可以按照如下操作:
1. //...省略其他代碼...
2. var $j = jQuery.noConflict(); //自定義一個比較短快捷方式
3. $j(function(){ //使用jQuery
4. $j("p").click(function(){
5. alert( $j(this).text() );
6. });
7. });
8.
9. $("pp").style.display = 'none'; //使用prototype
10. //...省略其他代碼...
可以自定義備用名稱,例如jq、$J、awesomequery--任何你想要的名稱都行。
如果不想給jQuery自定義這些備用名稱,還是想使用$而不管其它庫的$方法,同時又不想與其它庫相沖突,那麼可以使用如下兩種解決方法:
其一:1. //...省略其他代碼...
2. jQuery.noConflict(); //将變量$的控制權讓渡給prototype.js
3. jQuery(function($){ //使用jQuery
4. $("p").click(function(){ //繼續使用 $ 方法
5. alert( $(this).text() );
6. });
7. });
8.
9. $("pp").style.display = 'none'; //使用prototype
10. //...省略其他代碼...
其二:1. //...省略其他代碼...
2. jQuery.noConflict(); //将變量$的控制權讓渡給prototype.js
3. (function($){ //定義匿名函數并設定形參為$
4. $(function(){ //匿名函數内部的$均為jQuery
5. $("p").click(function(){ //繼續使用 $ 方法
6. alert($(this).text());
7. });
8. });
9. })(jQuery); //執行匿名函數且傳遞實參jQuery
10.
11. $("pp").style.display = 'none'; //使用prototype
12. //...省略其他代碼...
二, jQuery庫在其它庫之前導入
如果jQuery庫在其它庫之前就導入了,那麼可以直接使用"jQuery"來做一些jQuery的工作。同時,可以使用"$"方法作為其它庫的快捷方式。這裡沒有必要調用jQuery.noConflict()函數。
示例如下:
1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3. <html>
4. <head>
5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
6. <title>沖突解決5</title>
7. <!--先導入jQuery -->
8. <script src="../../scripts/jquery-1.3.1.js" type="text/javascript"></script>
9. <!--後導入其他庫 -->
10. <script src="prototype-1.6.0.3.js" type="text/javascript"></script>
11. </head>
12. <body>
13. <p id="pp">test---prototype</p>
14. <p >test---jQuery</p>
15.
16. <script type="text/javascript">
17. jQuery(function(){ //直接使用 jQuery ,沒有必要調用"jQuery.noConflict()"函數。
18. jQuery("p").click(function(){
19. alert( jQuery(this).text() );
20. });
21. });
22.
23. $("pp").style.display = 'none'; //使用prototype
24. </script>
25. </body>
26. </html>