jQuery简单的插件开发模式,分别为:
1、通过$.extend()来扩展jQuery
2、通过$.fn 向jQuery添加新的方法
3、通过$.widget()应用jQuery UI的部件工厂方式创建
一、$.extend()插件开发模式
$.extend({
sayHello: function(name) {
console.log('Hello,' + (name ? name : 'Dude') + '!');
}
})
$.sayHello(); //调用
$.sayHello('Wayou'); //带参调用
二、$.fn插件开发模式
$.fn.myPlugin = function(options) {
var defaults = {
'color': 'red',
'fontSize': '12px'
};
var settings = $.extend(defaults, options);//合并参数
return this.css({
'color': settings.color,
'fontSize': settings.fontSize
});
}
//调用
$('a').myPlugin({
'color': '#2C9929'
});
三、$.widget()插件开发模式
(function($, window, document,undefined) {
//定义Beautifier的构造函数
var Beautifier = function(ele, opt) {
this.$element = ele,
this.defaults = {
'color': 'red',
'fontSize': '12px',
'textDecoration': 'none'
},
this.options = $.extend({}, this.defaults, opt)
}
//定义Beautifier的方法
Beautifier.prototype = {
beautify: function() {
return this.$element.css({
'color': this.options.color,
'fontSize': this.options.fontSize,
'textDecoration': this.options.textDecoration
});
}
}
//在插件中使用Beautifier对象
$.fn.myPlugin = function(options) {
//创建Beautifier的实体
var beautifier = new Beautifier(this, options);
//调用其方法
return beautifier.beautify();
}
})(jQuery, window, document);
//调用
$(function() {
$('a').myPlugin({
'color': '#2C9929',
'fontSize': '20px',
'textDecoration': 'underline'
});
})