您應該構建您的插件,以便方法名稱可以作爲參數傳遞給您的插件。這是推薦的jQuery plugin authoring guide:
(function($) {
var methods = {
init: function(options) {
},
hello: function() {
return 1;
}
};
$.fn.myPlug = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.myPlug');
}
};
})(jQuery);
的使用會去是這樣的:
$("div").myPlug({ ... });
$("div").myPlug("hello"); // returns 1
我看不出有什麼不妥的地方。 – 2012-03-29 17:48:29