DIV CSS 佈局教程網

jQuery 的 $ 命名衝突:五種解法一次收錄
編輯:JQuery特效代碼     

最近踩到一個問題:同一頁同時引入 jQuery 與另一個 JS 函式庫後,用 $ 呼叫該函式庫的函數突然失效了。查了資料才發現是命名衝突 —— 許多 JavaScript 函式庫(如 Prototype)都把 $ 當成函數或變數名稱,jQuery 也不例外。

其實 $ 只是 jQuery 的別名。若同一頁需要使用 jQuery 以外的函式庫,可以呼叫 $.noConflict() 把 $ 的控制權讓出去。以下五種解法,總有一種適合你的專案。

解法一:把 $ 讓給別人,全部改用 jQuery

<!-- 引入 prototype -->
<script src="prototype-1.6.0.3.js" type="text/javascript"></script>
<!-- 引入 jQuery -->
<script src="/scripts/jquery-1.3.1.js" type="text/javascript"></script>

jQuery.noConflict();  // 把 $ 的控制權讓給 prototype.js
jQuery(function(){  // 這裡開始使用 jQuery
  jQuery("p").click(function(){
    alert( jQuery(this).text() );
  });
);
$("pp").style.display = 'none';  // 這裡使用 prototype

解法二:自訂一個短別名

var $j = jQuery.noConflict();
$j(function(){
  $j("p").click(function(){
    alert( $j(this).text() );
  });
);
$("pp").style.display = 'none';  // 使用 prototype

解法三:把 $ 當參數傳進 ready 回呼

jQuery.noConflict();
jQuery(function($){  // 這個作用域內的 $ 就是 jQuery
  $("p").click(function(){
    alert( $(this).text() );
  });
);
$("pp").style.display = 'none';  // 使用 prototype

解法四:用匿名函數包住整個區塊

jQuery.noConflict();
(function($){  // 定義匿名函數,形參名為 $
  $(function(){  // 閉包內部的 $ 一律代表 jQuery
    $("p").click(function(){
      alert( $(this).text() );
    });
  });
})(jQuery);  // 立刻執行並傳入 jQuery
$("pp").style.display = 'none';  // 使用 prototype

這也是日後寫 jQuery 插件時最推薦的包裹方式,變數不會污染全域。

解法五:調整載入順序

<!-- 先引入 jQuery -->
<script src="/scripts/jquery-1.3.1.js" type="text/javascript"></script>
<!-- 後引入其他函式庫 -->
<script src="prototype-1.6.0.3.js" type="text/javascript"></script>

jQuery(function(){  // 後者會覆蓋 $,因此這裡直接寫 jQuery
  jQuery("p").click(function(){
    alert( jQuery(this).text() );
  });
);
$("pp").style.display = 'none';  // 使用 prototype

五種做法各有適用場合:專案小、風格單純時解法一最省事;要在既有大量 jQuery 程式碼中最小改動,解法三與解法四最實用。有需要的人自行取用即可。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved