2012-04-02 79 views
0

因此,讓我們從情境開始。我有一個網站,它使用Jquery 1.4.2作爲Jquery的主要版本。 但用戶可以使用使用其他版本(1.2.1,1.5.1等)的自定義模板。所以它在某些情況下帶來衝突。
例如,這裏使用不同的Jquery版本無衝突

//included in my main view 
<script type="text/javascript" src="jquery-1.4.2.min.js" ></script> 
<script type="text/javascript"> 
     $(function() { 
       alert($().jquery); 
      }); 
</script> 

//included in custom template 
<script type='text/javascript' src='jquery-1.5.1.min.js'></script> 
<script type="text/javascript"> 
     $(function() { 
      alert($().jquery); 
     }); 
</script> 

所以兩者都被提醒1.5.1(因爲當文件準備初始化的)。所以我想要防止這種情況。

現在我只有一次在我腦海中的解決方案 - 使用noConflict(true)和更改所有$Jquery符號來新符號在我的網站上使用的所有插件。
是否有更優雅的解決方案,或者我真的需要重新命名我的網站中使用的所有插件?

P.S.另一種方式可能會使用向後兼容性插件,但在這種情況下,我需要包含很多插件才能與所有版本兼容。

+0

如果插件結構合理,他們將利用其在定義'jQuery'對象那一刻。所以你只需要按正確的順序加載它們。爲了在你自己的代碼中使用正確的版本,'ready'回調函數會傳遞一個對jQuery的引用作爲第一個參數。 – 2012-04-02 12:59:01

+0

在我的示例中,第一個警報獲取的是1.5.1而不是1.4.2,我想這種情況可能會出現在很多插件中。 – 2012-04-02 13:00:34

+1

但是插件通常被定義爲'(function($){...}(jQuery))',即插件'$'指的是當前引用的任何'jQuery'。在你的情況下,otoh,你正在訪問**全局**'$',後來被第二個jQuery腳本覆蓋。你的情況相當於'$(function($){...})'。試一試。 – 2012-04-02 13:01:44

回答

4

jQuery.noConflict()

**//included in my main view** 
<script type="text/javascript" src="jquery-1.4.2.min.js" ></script> 
<script type="text/javascript"> 
     $(function() { 
       alert($().jquery); 
      }); 
</script> 

**//included in custom template** 
<script type='text/javascript' src='jquery-1.5.1.min.js'></script> 
<script type="text/javascript"> 
     $151 = jQuery.noConflict(); 
     $151(function ($) { // In this scope $ === $151, or jQuery 1.5.1 
      alert($().jquery); 
      // $ !== jQuery. 
      // $().jquery = 1.5.1 
      // jQuery().jquery = 1.4.2 
     }); 
     // outside the scope 
     // $ === jQuery 
     // $().jquery returns 1.4.2 
</script> 

如何使用jQuery.noConflict();

$.noConflict()返回的jQuery的副本,你可以捕捉它的變量,像這樣:

var j = $.noConflict()

HTML:

<script type="text/javascript" src="jquery-1.4.2.min.js" ></script> 
<script type='text/javascript' src='jquery-1.5.1.min.js'></script> 

的JavaScript:

// jQuery === $ 
//$().jquery === 1.5.1 

jQ151 = $.noConflict(); 

// jQ151 !== $ 
// jQ151().jquery === 1.5.1 
// $().jquery === 1.4.2 

jQuery.ready(function() {..

或者乾脆jQuery(function() {..第一個參數是jQuery的的本地副本:

<script type="text/javascript" src="jquery-1.4.2.min.js" ></script> 
<script type="text/javascript"> 
    jQuery(function($) { 
     // in this scope $ refers to jQuery version 1.4.2 
    }); 
</script> 
<script type='text/javascript' src='jquery-1.5.1.min.js'></script> 

<script type="text/javascript"> 
    jQuery(function($) { 
     // in this scope $ refers to jQuery version 1.5.1 
    }); 
</script> 
+0

爲什麼要投票? – andlrc 2012-04-02 13:00:26

+0

已投票。如果出現錯誤,請在投票結束後說明! :) – 2012-04-02 13:00:49

+0

在這個問題我已經寫了關於noConflict和重命名$'s和jQuery的。問題在於尋找更優雅的方式。 – 2012-04-02 13:01:45