2012-04-17 91 views
1

看看jQuery的[插件/創作] [1]文檔我發現一些問題。我需要創建一個插件,可以讓我做到以下幾點:jQuery插件骷髏

$('#one').plug({foo:'bar'}); 
$('#two').plug(); 

根據我的文檔:

(function($){ 

    var settings = { 
     foo:'' 
    }; 
    var methods = { 
     init:function(options){ 
      return this.each(function(){ 
       $.extend(settings, options); 

       //------ Problem ----------// 
       alert(settings.foo); 

      }); 
     } 
    }; 
    $.fn.plug = function(method){ 
     //... 
    } 

})(jQuery); 

問題:$('#one').plug({foo:'bar'});警報「欄」的預期,但下一行不返回一個空字符串,它也返回「bar」。

+0

設置的obj不在你的插件範圍內。如果你去JS控制檯並輸入設置,你應該得到它。你realyl不應該。您應該正確閱讀文檔。或者您需要在某個時間重新設置設置。 – xotix 2012-04-17 12:28:44

+0

如果我需要本地插件實例的值,通過用戶默認設置在'init'方法中設置並且可以在插件實例的其他方法中訪問,我應該怎麼做? – Siavash 2012-04-23 10:42:14

+0

如果你想要在你的插件的範圍之外有一個變量,實際上你做得很對。你再次得到「酒吧」的原因是因爲它是從最後一次通話中保存的。由於設置不在插件內,它不會被重置(簡單地說)。所以你必須去設置='';或者在你的插件開始時使用類似的東西,或者在你的插件中創建你的var。我沒有JS的破解,所以你可能會問freenode服務器上的#jquery(irc)是否有freenode的web聊天。 – xotix 2012-04-23 14:53:02

回答

1

想我應該把這個問題發佈給任何人。有很多方法可以創建一個jQuery插件。我現在經常使用的是這種骨架:

(function($, window, document, undefined){ 

    function Skeleton(element, options){ 
     this.$element = $(element); 
     this.options = options; 

     // Plugin init goes here... 

    } 

    Skeleton.prototype = { 
     // Plugin methods 
     sampleMethod: function(){ 
      // ... 
     } 

    }; 
    // Plugin Definition // 
    $.fn.skeleton = function(options){ 
     if(typeof options == 'string'){ 
      var plugin = this.data('skeleton'); 
      if(plugin){ 
       var r = plugin[options].apply(plugin, Array.prototype.slice.call(arguments, 1)); 
       if(r) return r 
      } 
      return this 
     } 

     options = $.extend({}, $.fn.skeleton.defaults, options); 

     return this.each(function(){ 
      var plugin = $.data(this, 'skeleton'); 
      if(! plugin){ 
       plugin = new Skeleton(this, options); 
       $.data(this, 'skeleton', plugin); 
      } 
     }); 
    }; 
    $.fn.skeleton.defaults = { 
     // Plugin options ... 
    }; 

})(jQuery, window, document); 
+0

偉大的骨架,但最終你需要做一個默認選項: > plugin = new CollapsiblePanel(this,$ .extend({},options)); – Echilon 2017-01-26 13:35:04