歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> jQuery與其他庫沖突的解決方法

jQuery與其他庫沖突的解決方法

日期:2017/3/1 11:03:15   编辑:Linux編程

在使用jQuery開發的時候,可能還會使用到其他的JS庫,比如Prototype,但多庫共存時可能會發生沖突;若是發生沖突後,可以通過以下幾種方案進行解決:

一、 jQuery庫在其他庫之前導入,直接使用jQuery(callback)方法如:

Html代碼
  1. <html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  4. <!--先導入jQuery -->
  5. <script src="../../scripts/jquery-1.3.1.js" type="text/javascript"></script>
  6. <!--後導入其他庫 -->
  7. <script src="prototype-1.6.0.3.js" type="text/javascript"></script>
  8. </head>
  9. <body>
  10. <p id="pp">test---prototype</p>
  11. <p >test---jQuery</p>
  12. <script type="text/javascript">
  13. jQuery(function(){ //直接使用 jQuery ,沒有必要調用"jQuery.noConflict()"函數。
  14. jQuery("p").click(function(){
  15. alert( jQuery(this).text() );
  16. });
  17. });
  18. $("pp").style.display = 'none'; //使用prototype
  19. </script>
  20. </body>
  21. </html>

二、 jQuery庫在其他庫之後導入,使用jQuery.noConflict()方法將變量$的控制權讓渡給其他庫,有以下幾種方式:

Js代碼
  1. <script type="text/javascript">
  2. jQuery.noConflict(); //將變量$的控制權讓渡給prototype.js
  3. jQuery(function(){ //使用jQuery
  4. jQuery("p").click(function(){
  5. alert( jQuery(this).text() );
  6. });
  7. });
  8. $("pp").style.display = 'none'; //使用prototype
  9. </script>
  10. //代碼二
  11. <script type="text/javascript">
  12. var $j = jQuery.noConflict(); //自定義一個比較短快捷方式
  13. $j(function(){ //使用jQuery
  14. $j("p").click(function(){
  15. alert( $j(this).text() );
  16. });
  17. });
  18. $("pp").style.display = 'none'; //使用prototype
  19. </script>
  20. //代碼三
  21. <script type="text/javascript">
  22. jQuery.noConflict(); //將變量$的控制權讓渡給prototype.js
  23. jQuery(function($){ //使用jQuery
  24. $("p").click(function(){ //繼續使用 $ 方法
  25. alert( $(this).text() );
  26. });
  27. });
  28. $("pp").style.display = 'none'; //使用prototype
  29. </script>
  30. //代碼四
  31. <script type="text/javascript">
  32. jQuery.noConflict(); //將變量$的控制權讓渡給prototype.js
  33. (function($){ //定義匿名函數並設置形參為$
  34. $(function(){ //匿名函數內部的$均為jQuery
  35. $("p").click(function(){ //繼續使用 $ 方法
  36. alert($(this).text());
  37. });
  38. });
  39. })(jQuery); //執行匿名函數且傳遞實參jQuery
  40. $("pp").style.display = 'none'; //使用prototype
  41. </script>
  42.  
    通過以上幾方法就可以很好的去解決多庫共存會發生沖突的問題了.
Copyright © Linux教程網 All Rights Reserved