| 類型 | 掛載位置 | 呼叫方式 | 適用場景 |
|---|---|---|---|
| 全域函式 | jQuery.fn / jQuery | $.fn.method() / $.method() | 工具函式、命名空間管理 |
| 實例方法 | jQuery.fn | $(selector).method() | DOM 元素操作、鏈式呼叫 |
jQuery.sayHello = function(name) {
alert(name + ' 您好');
};
// 呼叫
$.sayHello('小明'); // 或 jQuery.sayHello('小明')
jQuery.extend() 批次擴充jQuery.extend({
min: function(a, b) { return a < b ? a : b; },
max: function(a, b) { return a > b ? a : b; }
});
$.min(2, 3); // 2
$.max(4, 5); // 5
jQuery.extend(object) 直接擴充 jQuery 命名空間本身。
jQuery.fn)jQuery.fn.sayHello = function(name) {
return this.each(function() {
alert(name + ' 您好,我是 ' + this.tagName);
});
};
// 呼叫:針對每個匹配元素執行
$('div').sayHello('訪客');
關鍵:回傳this(jQuery 物件)以支援鏈式呼叫;內部用this.each()遍歷匹配集合。
jQuery.fn.extend() 批次新增插件jQuery.fn.extend({
check: function() {
return this.each(function() { this.checked = true; });
},
uncheck: function() {
return this.each(function() { this.checked = false; });
}
});
// 使用
$('input[type=checkbox]').check();
$('input[type=radio]').uncheck();
(function($) {
var pluginName = 'myPlugin';
var defaults = {
color: 'red',
speed: 300,
onComplete: $.noop
};
function Plugin(element, options) {
this.element = element;
this.$el = $(element);
this.settings = $.extend({}, defaults, options);
this._init();
}
Plugin.prototype = {
_init: function() {
this.$el.css('color', this.settings.color);
this._bindEvents();
},
_bindEvents: function() {
this.$el.on('click.' + pluginName, $.proxy(this._onClick, this));
},
_onClick: function() {
this.$el.fadeOut(this.settings.speed, this.settings.onComplete);
},
destroy: function() {
this.$el.off('.' + pluginName).removeData(pluginName);
}
};
// 掛載至 jQuery.fn
$.fn[pluginName] = function(options) {
var args = Array.prototype.slice.call(arguments, 1);
return this.each(function() {
var instance = $.data(this, pluginName);
if (!instance) {
instance = new Plugin(this, options);
$.data(this, pluginName, instance);
}
if (typeof options === 'string' && typeof instance[options] === 'function') {
instance[options].apply(instance, args);
}
});
};
})(jQuery);
// 使用範例
$('.box').myPlugin({ color: 'blue', speed: 500 });
$('.box').myPlugin('destroy');
this(除非刻意回傳特定值)。$.extend({}, defaults, options) 避免污染預設物件。.on('click.myplugin'),銷毀時精準解綁。.data():實例掛載於元素,避免全域變數污染。$(sel).plugin('method', arg) 模式。$ 參數相容 noConflict。