2014-02-07 59 views
0

我開發一個插件,添加對象我想打電話給外界一些活動,以同一個對象插件後,我怎麼能做到這一點呼叫嵌套函數相同的對象

(function ($, undefined) { 

    jQuery.fn.pluginname = function (options) { 
     var set = $.extend({ 
      opacity: 0.5    
     }, options); 

     //if(options.type) 

     var cdiv = this; 
     cdiv.css("opacity",set.opacity); 

     function callthis() 
     { 
      cdiv.css("display","none"); 
     } 
    } 
})(jQuery); 


jQuery("#first").pluginname({opacity:0.5}); 

jQuery("#second").pluginname({opacity:0.5}); 

// call this function later 

jQuery("#first").pluginname("callthis"); 

回答

0

通常的方法是讓您的插件接受「方法」作爲字符串參數,例如:

jQuery("#first").pluginname("callThis"); 

在插件的內部,您將該請求路由到該函數。

通常情況下,您還需要將最初使用的選項存儲在除關閉處以外的地方; data對此很有用。

而你通常有一個"destroy"方法從元素中刪除插件。

所以:

(function ($, undefined) { 
    var methods = { 
     init: function(options) { 
      // Determine options 
      var opts = $.extend({ 
       opacity: 0.5    
      }, options); 

      // Remember them 
      this.data("pluginname", opts); 

      // Initial stuff 
      this.css("opacity", opts.opacity); 
     }, 

     callThis: function(opts) { 
      // Use 'opts' if relevant 
      this.css("display","none"); 
     }, 

     destroy: function(opts) { 
      this.removeData("pluginame"); 
      this.css("display", "").css("opacity", ""); 
     } 
    }; 

    jQuery.fn.pluginname = function (options) { 
     var method, args; 

     // Method? 
     if (typeof options === "string") { 
      // Yes, grab the name 
      method = options; 

      // And arguments (we copy the arguments, then 
      // replace the first with our options) 
      args = Array.prototype.slice.call(arguments, 0); 

      // Get our options from setup call 
      args[0] = this.data("pluginname"); 
      if (!args[0]) { 
       // There was no setup call, do setup with defaults 
       methods.init.call(this); 
       args[0] = this.data("pluginname"); 
      } 
     } 
     else { 
      // Not a method call, use init 
      method = "init"; 
      args = [options]; 
     } 

     // Do the call 
     methods[method].apply(this, args); 
    }; 
})(jQuery); 

Live Example | Source

0

試試這個:

(function ($, undefined) { 

    jQuery.fn.pluginname = function (options) { 
     var set = $.extend({ 
      opacity: 0.5    
     }, options); 

     //if(options.type) 
     if(typeof options == function){ 
     return function callthis() 
     { 
      cdiv.css("display","none"); 
     } 
     } else{ 
     return function(){ 
     var cdiv = this; 
     cdiv.css("opacity",set.opacity); 
     } 
     } 


    } 
})(jQuery);