2012-11-27 109 views
0

好吧,所以我不能得到它如何跨jQuery插件共享設置,無論我做什麼我的設置獲取覆蓋時,循環槽元素。這裏是我的代碼:jquery插件問題

(function ($) { 
    var default_settings = { 
     auto_start: false, 
     tools: {} 
    }; 

    function test(settings){ 
     //here is the problem it gets wrong element 
     settings.tools.progress_bar.animate({ 
      width: "100%" 
     }); 
    } 

    var methods = { 
     init: function(element, options){ 
      var settings = $.extend({}, default_settings, options); 

      settings.tools.progress_bar = $('<div class="test"></div>'); 

      $(element).append(
       settings.tools.progress_bar 
      ); 

      if(settings.auto_start) 
       test(settings); 

      $.data(element, "settings", settings); 
     }, 

     start: function(){ 
      var settings = $.data(this, "settings"); 

      test(settings); 
     } 
    } 

    $.fn.ajaxupload = function(method, options){ 
     return this.each(function(){ 
      if(methods[method]) 
       return methods[method].apply(this, [options]); 
      else if(typeof method === 'object' || !method) 
       return methods.init(this, method); 
     }); 
    } 
})(jQuery); 

我需要能夠循環通過多個元素,後來就調用公共職能,開始了一些行動或別的東西,像這樣:

$(".container").ajaxupload(); 

$(".container2").ajaxupload(); 

//even though I call for container it will run animation for container2 
$(".container").ajaxupload("start"); 

我也有取得了jsfiddle,但至少對我來說目前還沒有效果。

回答

2

的simpy更換

var settings = $.extend({}, default_settings, options); 

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

演示:http://jsfiddle.net/jupSp/12/

不深拷貝(第一個參數爲true)它只複製你的情況的對象和第一級是導致 settings.tools指向default_settings.tools並致電settings.tools.progress_bar = $('<div class="test"></div>'); you ov erride default_settings.tools.progress_bar並將最後一個progress_bar附加到所有元素。