jquery 扩展
jQuery 扩展方法
jQuery 扩展允许开发者自定义 jQuery 的功能,添加新的方法或插件。以下是常见的扩展方式:

扩展 jQuery 对象方法
通过 $.fn 扩展 jQuery 对象方法,所有 jQuery 实例均可调用:

$.fn.myPlugin = function(options) {
// 默认配置
const settings = $.extend({
color: 'red',
fontSize: '14px'
}, options);
// 遍历匹配的元素
return this.each(function() {
$(this).css({
color: settings.color,
fontSize: settings.fontSize
});
});
};
// 调用
$('p').myPlugin({ color: 'blue' });
扩展工具方法
通过 $ 或 jQuery 直接扩展工具方法,作为静态函数使用:
$.myUtility = function(str) {
return str.toUpperCase();
};
// 调用
console.log($.myUtility('hello')); // 输出 "HELLO"
插件开发规范
- 命名唯一性:避免与其他插件冲突,建议使用命名空间(如
myPlugin)。 - 链式调用:确保插件返回
this以支持链式调用。 - 默认配置:提供可覆盖的默认参数。
- 单一职责:每个插件只解决一个问题。
示例:表单验证插件
$.fn.validateForm = function(rules) {
return this.each(function() {
const $form = $(this);
$form.on('submit', function(e) {
let isValid = true;
$.each(rules, function(field, rule) {
const $field = $form.find(`[name=${field}]`);
if (!rule.test($field.val())) {
isValid = false;
$field.addClass('error');
}
});
if (!isValid) e.preventDefault();
});
});
};
// 调用
$('#myForm').validateForm({
email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
password: /^.{6,}$/
});
注意事项
- 避免污染全局:所有扩展应封装在 jQuery 对象内。
- 性能优化:减少 DOM 操作,缓存选择器结果。
- 兼容性:确保扩展方法在不同 jQuery 版本中正常工作。
通过合理扩展 jQuery,可以显著提升代码复用性和开发效率。






