<script> console.log($); ;(function($){ // 設置默認值 var defaults = { background:'#ccc', width:'100px', height:'100px' }; // 將方法都放在一個命名空間中 var method ={ init:function(options){ var defaults = { background:'#ccc', width:'100px', height:'100px' }; var settings =$.extend({},defaults,options); this.css( { background:settings.background, width:settings.width, height:settings.height}); console.log("init"); }, show:function(options){ var settings =$.extend({callback: function(p) {console.log(p);}},defaults,options); var p ="1111"; settings.callback.call(this,p); // 上面那種是回調函數封裝在對象裏面,記得須要從新指定this // 加入回調函數的話須要從新改變this指向新的調用者,當單獨傳遞一個回調函數 // call the callback and apply the scope: // if(typeof callback == 'function'){ // callback.call(this); // } this.css( { background:settings.background, width:settings.width, height:settings.height}); options= settings; console.log("show"); this.show(1000).slideUp(2000).slideDown(1000); }, hide:function(){ this.hide(1000); console.log("hide"); }, fadeIn:function(content){ console.log(1); console.log(content); console.log("fadein"); } }; $.fn.demo = function(action,callback){ if(method[action]){ return method[action].apply(this,Array.prototype.slice.call(arguments,1)); // 將類數組參數的第一個參數是方法名切掉,剩下的切爲數組 }else if(typeof action==='object' || ! method[action]){ // 若是傳進來的是空對象或則非字符串 return method.init.apply(this,arguments); }else{ $.error('Method'+action+'does not exist on plugin !'); } } })(jQuery); </script> <script> $("div").demo('show',{ background:'#53ff53', width:'100px', height:'100px',callback:function(ab){ console.log(this); if(ab){ console.log(1); }else{ console.log(ab) } this.css({"color":"#f00","lineHeight":"40px"}); } }); </script>
reference:
https://stackoverflow.com/questions/1117086/how-to-create-a-jquery-plugin-with-methods?answertab=votes#tab-topcss
https://stackoverflow.com/questions/2534436/jquery-plugin-adding-callback-functionality
帶參數
https://coderwall.com/p/gnkbzq/adding-a-callback-handler-to-a-jquery-pluginjquery