我创建了一个免费的jQuery插件,我想要做的是创建一些可以为我的客户付款的附加组件。
所以,让我们假设我免费提供的免费jQuery插件将hello world添加到html div
标记中,我想创建一个加载项,使div
背景颜色变为红色
免费版插件:
(function(window, $) {
var example = function(elem, options) {
this.elem = elem;
this.$elem = $(elem);
this.options = options;
this.metadata = this.$elem.data('example-options');
};
example.prototype = {
defaults: {
message: 'Hello world!'
},
init: function() {
this.config = $.extend({}, this.defaults, this.options, this.metadata);
this.displayMessage();
return this;
},
displayMessage: function() {
this.$elem.append('<h1>'+this.config.message+'</h1>');
}
}
example.defaults = example.prototype.defaults;
$.fn.example = function(options) {
return this.each(function() {
new example(this, options).init();
});
};
window.example = example;
})(window, jQuery);
我想创建一个将在不同的js文件中的插件,如下所示:
example.prototype = {
bgColor: function() {
this.$elem.css('background-color', '#f00');
}
};
我该怎么做?
答案 0 :(得分:1)
不是替换您创建的默认prototype
,而只需添加它并覆盖您希望更改的方法。例如,您可以将bgColor
方法添加到prototype
,如下所示:
example.prototype.bgColor = function() {
this.$elem.css('background-color', '#f00');
};
要覆盖提供增强功能的方法,您可以这样做:
example.prototype.displayMessage = function() {
this.$elem.append('<h1>This message comes from the add-on</h1>');
}
请注意,要使其正常工作,附加的js文件将包含在默认的插件js文件之后。