Jquery與其它js框架(MooTools以及Prototype、Dojo、YUI等等)之間共享衝突的解決辦法

轉自:zend實驗室

注:jquery官方原文:Using jQuery with Other Libraries


本篇文章將幫助你解決Jquery與其它js框架之間的共享衝突的問題,實現jquery與Mootools之間的共存。最近在做一些關於CRM的界面,其中用到了一套界面庫,是以Mootools爲基礎開發的,但是後來考慮需要引入一些新的組件,並且這些組件都是以jquery爲基礎開發的,如leightbox等。結果引入jquery之後卻發現$在兩個框架中都有各自的定義,衝突也顯現出來了。經過收集,網上大致提供了三種解決辦法。

方法一、

 

<html>
  <head>
    <script src="Mootools.js"></script>
    <script src="jquery.js"></script>
    <script>
      jQuery.noConflict();//釋放jquery中$定義,並直接使用jQuery代替平時的$
      jQuery(document).ready(function(){
        jQuery("div").hide();
      });
      $('someid').style.display = 'none';//此處中的$爲原Mootools中的$,使用方法不變
    </script>
  </head>
  <body>
  </body>
  </html>

 

方法二、

 

<html>
   <head>
     <script src="Mootools.js"></script>
     <script src="jquery.js"></script>
     <script>
       jQuery.noConflict();  
       //將你使用的jquery代碼放到document ready方中
       jQuery(document).ready(function($){
         // 此處爲jQuery的$定義
         $("div").hide();
      });  
       //此處爲Mootools的定義
      $('someid').style.display = 'none';
     </script>
   </head>
   <body>
   </body>
</html>

 

方法三、

 

 <html>
  <head>
     <script src="Mootools.js"></script>
     <script src="jquery.js"></script>
    <script>
      var $j = jQuery.noConflict();//以$j來替代jQuery中的$,同時區分mootools
        $j(document).ready(function(){
        $j("div").hide();
        });
       $('someid').style.display = 'none';  //原mootools中的$照舊使用
    </script>
  </head>
  <body></body>
  </html>

 

  zend實驗室強烈建議你使用第三中方法來解決jquery與其它js框架之間共享衝突問題,理由是它既簡短,又能實現你想要的結果,並且不會像第二個方法中那樣存在使用位置限制。想在哪用就在哪用,隨心所欲。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章