编写一个更好的jQuery插件 [英] Writing a better jQuery plugin
本文介绍了编写一个更好的jQuery插件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前我有我的jQuery插件运行它的逻辑if statments。
at the moment I have my jQuery plugin running it's logic in if statments.
例如我有:
(function($) {
$.fn.myplugin = function(action) {
if(action == "foo"){
}
if(action == "bar"){
}
if(action == "grapefruits"){
}
}
})(jQuery);
有更好的方法吗?
与事件处理程序一样,我可以在插件中声明它们吗?
Also the same with event handlers, can I declare them inside the plugin?
推荐答案
您可以将不同的功能存储在一个对象并使用索引器,如下所示:
You can store different functions in an object and use an indexer, like this:
(function($) {
var methods = {
foo: function(action) { ... },
bar: function(action, someParam) { ... },
grapefruits: function(action, param1, param2) { ... },
...
};
$.fn.myplugin = function(action) {
methods[action].apply(this, arguments);
}
})(jQuery);
这篇关于编写一个更好的jQuery插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文