2012-11-27 111 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附加到所有元素。