2011-05-27 42 views
5

我做了一個jQuery插件,它的工作非常好。除了當我在同一頁面上有多個實例時,最後一個實例的選項/設置用於兩者。默認和多個實例的jquery設置

這是一個精簡版...它的長度很抱歉。

(function() { 

    var settings = {}; 
    var defaults = { 
     duration : 1000, 
     easingShow : 'easeOutBounce', 
     easingHide : 'easeOutQuad' 
    }; 

    var methods = { 
     init : function(options) { 

      return this.each(function(n) { 

       settings = $.extend(defaults, options); 

      }); 

     }, 

     show : function() { 

      // settings used here 
     }, 

     hide : function() { 
      // also used here 
     } 
    }; 

    $.fn.expander = function(method) { 

     if (methods[method]) { 
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); 
     } else if (typeof method === 'object' || !method) { 
      return methods.init.apply(this, arguments); 
     } else { 
      $.error('Method ' + method + ' does not exist on jQuery.expander'); 
     } 

    }; 

})(jQuery); 

我敢肯定,這是某種名稱空間問題,因爲我經常會感到困惑。

由於

回答

6

使用

settings = $.extend(true, {}, defaults, options); 

從jquery的文檔@http://api.jquery.com/jQuery.extend/

 
deep  If true, the merge becomes recursive (aka. deep copy). 
target The object to extend. It will receive the new properties. 
object1 An object containing additional properties to merge in. 
objectN Additional objects containing properties to merge in. 

記住目標對象(第一自變量)將被修改,並且也將從$ .extend()返回。但是,如果我們想保留兩個原始對象,我們可以通過傳遞一個空對象作爲目標來實現。

爲每個元件具有不同的設置,你可以在使用.data()

檢查了工作演示的每個元素將它們存儲:http://jsfiddle.net/roberkules/XvKs8/

+0

謝謝,但我想你已經錯過了問題。問題不在於我設置設置變量的方式。這是,如果我把它設置在'return this.each(function(){});'部分,那麼顯示和隱藏功能將無法訪問它。但是如果我將它設置在外面,就像我已經完成的那樣,每個啓用了插件的元素都是相同的。 – ianbarker 2011-05-31 08:14:26

+0

檢查演示,應該做你需要的。 – roberkules 2011-05-31 10:56:06

+1

我曾試圖避免使用數據(),但我認爲這是唯一的方法。 – ianbarker 2011-05-31 14:12:09