JQuery Plugin Defaults and Options

你说的曾经没有我的故事 提交于 2019-12-06 03:47:01

问题


How can I turn the following properties / variables in my plugin into defaults and options that can be set from document ready?

// plugin js:

(function($){
   $.fn.myPlugin = function(options){
      var myForm = this;
      myForm.variable1 = true;
      myForm.variable2 = true;
      myForm.variable3 = true;
      myForm.variable4 = true;

      ...

      if(myForm.variable1){
         // do something
      }

      ...
   }
})(jQuery);

// document ready in page:

<script type="text/javascript">
   $(document).ready(function() {
      $('#form1').myPlugin();
   });
</script>

回答1:


The simplest pattern is to extend a default options object. But it does mean that any parameters have to be passed together as an "option" object, eg: myPlugin({variable2:false})

(function($){
   $.fn.myPlugin = function(options){

      var defaults = {
          variable1 : true,
          variable2 : true,
          variable3 : true,
          variable4 : true
      }

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

      if(settings.variable1){
         // do something
      }

      ...
   }
})(jQuery);



回答2:


See following:

$('#form1').myPlugin({variable1 : true, variable2: false....});

and use

(function($){
   $.fn.myPlugin = function(options){

     options.variable1 = true;
          options.variable2 = true;
          options.variable3 = true;
          options.variable4 = true;
  }
})(jQuery);

For proper way see

http://jquery-howto.blogspot.com/2009/01/how-to-set-default-settings-in-your.html



来源:https://stackoverflow.com/questions/8905507/jquery-plugin-defaults-and-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!