我有一个简单的插件,它有init,close和open函数。我有一个调用这个插件的html模板数组。只是对于某个模板,我想对这个插件做一些稍微不同的行为,比如说可以在open函数中添加一个不同的类,并在关闭时删除相同的类。什么是做这件事的优雅方式?我应该找到html的id并在同一个插件的open和close函数中做一个if else,或者有更好的方法吗?如何调用具有稍微不同行为的插件?
;(function ($, window, document, undefined) {
function Plugin(element, options) {
Window = this;
this.element = element;
this._name = pluginName;
this.init(element);
}
Plugin.prototype = {
init: function(element) {
},
close:function(e){
//removes a class and hides the element
},
open:function(element){
//adds a class and shows the element
}
}
//Extend Global jQuery (where we actually add the plugin!)
$.fn[pluginName] = function (options) {
plugin = $.data(window, 'plugin_' + pluginName);
if (!(plugin instanceof Plugin)) {
$.data(window, 'plugin_' + pluginName,
plugin = new Plugin(this, options));
}
return $Extend(this).each(function() {
$.data(this, 'plugin_' + pluginName, plugin);
});
};
}(jQuery, window, document));
或者使用大多数jQuery插件中使用的'extend()'成语将用户的选项合并到默认选项对象中。 – Barmar
您必须做的另一件事是记住每个元素使用的选项。这可以使用'data()'完成。 – Barmar
@Barmar两个好的指针。 – adamb