我正在使用jquery.boilerplate.js创建一个简单的自定义jQuery插件。现在我想创建一个名为
的函数var div1 = $("#div1").changeBackgroundColor({
color: $('#colorCode').val().trim()
});
div1.getColor();
如何在jquery插件中定义getColor()
方法。
自定义插件
;(function($, window, document, undefined) {
var pluginName = "changeBackgroundColor", defaults = {
color : "black"
};
function Plugin(element, options) {
this.element = element;
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
$.extend(Plugin.prototype, {
init : function() {
console.log("Hello");
}
});
$.fn[pluginName] = function(options) {
this.each(function() {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin(this,
options));
}
console.log(options);
if(options===undefined){
$(this).css("background-color", defaults.color);
} else{
$(this).css("background-color", options.color);
}
});
return this;
};
})(jQuery, window, document);
谢谢.... :)
答案 0 :(得分:1)
你有点错过了插件和OOP的全部内容。
$.fn[pluginName]
- 应该扮演基础架构角色并将实际工作委托给Plugin
实例。Plugin
实例应该使用element执行实际工作。Plugin
个实例上的方法,可以$.fn[pluginName]
处理options
为字符串时的特殊情况。 $(selector).changeBackgroundColor('methodToBeCalled' /*rest arguments*/)
;(function($, window, document, undefined) {
var pluginName = "changeBackgroundColor",
defaults = {
color : "black"
},
//methods to be called via $().changeBackgroundColor(name)
publicMethods = {
getColor: function() {
return this.settings.color;
},
setColor: function(color) {
this.settings.color = color;
this.element.css('background-color', color);
}
},
privateMethods = { //internal methods
init : function() {
console.log('init');
this.setColor(this.getColor());
}
};
function Plugin(element, options) {
this.element = $(element);
this.settings = $.extend({}, defaults, options);
this.init();
}
//copy private and public methods
$.extend(Plugin.prototype, privateMethods, publicMethods);
$.fn[pluginName] = function(options) {
var out = [],
args = [].slice.call(arguments, 1);
this.each(function() {
var plugin = $.data(this, pluginName),
method;
if (!plugin) { //create new plugin
plugin = new Plugin(this, options)
return $.data(this, pluginName, plugin);
}
//handle method calls
if(typeof options === 'string' && publicMethods[options]) {
out.push(plugin[options].apply(plugin, args));
}
});
return out.length ? (out.length === 1 ? out[0] : out) : this;
};
})(jQuery, window, document);
用法
$('#a').changeBackgroundColor();
$('#b').changeBackgroundColor({color: 'navy'});
$('#c').changeBackgroundColor({color: 'green'});
console.log($('#b').changeBackgroundColor('getColor'));
console.log($('#b, #c').changeBackgroundColor('getColor'));
$('#a').changeBackgroundColor('setColor', 'red');
console.log($('#a').changeBackgroundColor('getColor'));
答案 1 :(得分:0)
答案 2 :(得分:0)
像这样创建你的插件:
$.fn.highlight = function(){
this.css("background","yellow").css("color","black");
return this;
}
$(".highlight").highlight().fadeIn();