jquery扩展
jQuery 扩展方法
jQuery 扩展可以通过 $.extend() 或 $.fn.extend() 实现。前者用于扩展 jQuery 工具方法,后者用于扩展 jQuery 实例方法。
扩展工具方法(静态方法)
$.extend({
myPlugin: function() {
console.log('This is a utility method');
}
});
// 调用方式
$.myPlugin();
扩展实例方法(插件开发)
$.fn.extend({
myPlugin: function(options) {
// 默认配置
const defaults = {
color: 'red',
fontSize: '14px'
};
// 合并配置
const settings = $.extend({}, defaults, options);
return this.each(function() {
$(this).css({
color: settings.color,
fontSize: settings.fontSize
});
});
}
});
// 调用方式
$('div').myPlugin({ color: 'blue' });
最佳实践
命名空间 为避免与其他插件冲突,建议使用命名空间:

$.fn.myNamespace = {
myPlugin: function() {
// 插件逻辑
}
};
链式调用
保持 jQuery 链式调用特性,确保方法返回 this:
$.fn.myPlugin = function() {
return this.each(function() {
// 操作逻辑
});
};
参数处理 提供灵活的配置选项:

$.fn.myPlugin = function(options) {
const defaults = { /* 默认值 */ };
const settings = $.extend({}, defaults, options);
// 使用 settings 配置
};
高级扩展模式
立即执行函数 避免污染全局命名空间:
(function($) {
$.fn.myPlugin = function() {
// 插件逻辑
};
})(jQuery);
原型扩展 直接扩展 jQuery 原型:
$.fn.myPlugin = function() {
// 直接操作 jQuery 原型
};
插件封装 完整插件结构示例:
(function($) {
const Plugin = function(element, options) {
this.$element = $(element);
this.options = $.extend({}, defaults, options);
this.init();
};
Plugin.prototype = {
init: function() {
// 初始化逻辑
},
method: function() {
// 自定义方法
}
};
$.fn.myPlugin = function(options) {
return this.each(function() {
new Plugin(this, options);
});
};
const defaults = {
// 默认配置
};
})(jQuery);
这些方法提供了从基础到高级的 jQuery 扩展技术,可以根据需求选择合适的实现方式。






