jQuery 使用 $ 作為別名,當頁面引入多個 JS 庫(如 Prototype、MoTools、Zepto)時,$ 會被覆蓋導致衝突。本文系統梳理三種官方解決方案,並給出插件開發最佳實踐。
| 加載順序 | $ 歸屬 | jQuery 調用方式 |
|---|---|---|
| Prototype → jQuery | jQuery | $() 或 jQuery() |
| jQuery → Prototype | Prototype | 僅 jQuery() |
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
// 釋放 $,歸還給 Prototype
var $j = jQuery.noConflict(); // 返回 jQuery 引用,可自定義別名
// 此後 $ 為 Prototype,jQuery 必須用全稱或 $j
$j('#msg').hide(); // jQuery
$('msg').hide(); // Prototype 的 $
</script>
var $j = jQuery.noConflict();
$j(document).ready(function($) {
// 閉包內 $ 安全指向 jQuery
$('#msg').hide();
$('.box').fadeIn();
});
// 或立即執行函數
(function($) {
$('#msg').hide();
// 插件代碼...
})(jQuery);
jQuery.noConflict();
jQuery(document).ready(function($) {
// 此作用域內 $ 安全指向 jQuery
$('#msg').hide();
});
// 等價簡寫(推薦插件開發)
(function($) {
// 插件邏輯,內部 $ 絕對安全
$.fn.myPlugin = function() { ... };
})(jQuery);
;(function($, window, document, undefined) {
'use strict';
var pluginName = 'myPlugin';
var defaults = { color: 'red' };
function Plugin(element, options) {
this.element = element;
this.settings = $.extend({}, defaults, options);
this.init();
}
Plugin.prototype.init = function() {
// 初始化邏輯
};
$.fn[pluginName] = function(options) {
return this.each(function() {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin(this, options));
}
});
};
})(jQuery, window, document);
關鍵點:
; 防止前文遺漏分號導致報錯。undefined 保證 ES3 環境下 undefined 不被篡改。$.data 存儲實例,防止重複初始化。| 符號 | 含義 | 示例 |
|---|---|---|
| # | ID 選擇器 | $('#id') |
| . | Class 選擇器 | $('.class') |
| * | 通配符 | $('*') |
| , | 多選擇器並集 | $('.a, .b') |
| 空格 | 後代選擇器 | $('.parent .child') |
| > | 直接子元素 | $('.parent > .child') |
| ~ | 後續兄弟 | $('.prev ~ .next') |
| + | 緊鄰兄弟 | ('.prev + .next') |
| : | 偽類/過濾器 | (':first', ':visible') |
jQuery.noConflict() + IIFE 閉包傳參是解決 $ 衝突的標準方案。插件開發務必採用閉包模板,確保在任何加載順序、多庫共存環境下穩定運行。現代項目建議使用模塊化(ESM/CommonJS)徹底避免全局污染。