两种写法对比:
第一种:
;(function($){ $.fn.myplugin = function(op,params){ if (typeof op == ‘string‘){ return $.fn.myplugin.methods[op](this,params); } //默认参数 var settings = { "text" : "hehe", "color" : "red" } settings = $.extend(settings,op);//参数合并 return this.each(function(){ $(this).text(settings.text).css("color",settings.color); }); }; //暴露的API $.fn.myplugin.methods = { show : function(selector,params){ showText(); }, getValue : function(selector,params){ console.log("value is"+ params); } }; //静态方法 function showText(param){ alert(param); } })(jQuery);控件调用:
var m = $(".b").myplugin({ "text" : "haha", "color" : "yellow" }); m.myplugin("show","zhangsan"); m.myplugin("getValue","zhangsan");
第二种:
;(function($){ var $target; var settings = null; $.fn.myPlugin = function(options){ $target = $(this); if($.fn.myPlugin.methods[options]){ return $.fn.myPlugin.methods[options].apply(this,Array.prototype.slice.call(arguments,1)); }else if(typeof options == "object"||!options){ return $.fn.myPlugin.methods.init.apply(this,arguments); }else{ $.error("Methods"+options+"does not exist on jQuery.myPlugin"); } }; $.fn.myPlugin.methods = { init : function(op){ var defualt = { width : 100, heght : 50 }; settings = $.extend(defualt,op); myPluginInit(settings,$target); bindEvents(); return $target; }, getValue : function(){ return "000"; } }; function myPluginInit(settings,$target){ $target.width(settings.width); $target.height(settings.height); } function bindEvents(){ $(this).click(function(){ alert("click"); }); } })(jQuery);
时间: 2024-12-30 00:05:35