【问题标题】:Adding a param to a method in a plugin将参数添加到插件中的方法
【发布时间】:2025-12-18 15:25:06
【问题描述】:

我正在寻找一种在我的插件中为方法添加额外参数的方法。

这个例子我使用了一个更新方法,但是它需要一个额外的参数来告诉更新什么。

// 插件包装器

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

      var pluginName = 'myPlugin01';

      function Plugin(element, options){

          // vars here
      };

      Plugin.prototype = {

          init: function(){

          // init code here

          },
          update: function(param){

              // need the param value in this method
              if(param == 'bottom'){
                  alert('bottom it is...')
              }else{
                  alert('top it is...')
              }

          },
      };

      $.fn[pluginName] = function(option) {
          return this.each(function() {
              var $this   = $(this);
              var data    = $this.data(pluginName);
              var options = typeof option == 'object' && option;
              if (!data){ 
                $this.data(pluginName, (data = new Plugin(this, options)))
              }
              if (typeof option == 'string'){
                   data[option]();
              }
          });
      };

      $.fn[pluginName].defaults = {
          option1: true
      };

  })(jQuery, window, document);

//我想怎么使用它

$('.element').myPlugin('update','bottom');

【问题讨论】:

    标签: javascript jquery plugins methods


    【解决方案1】:

    不确定您要做什么,但您可以向 $.fn[pluginName] 添加额外的 arg 并将其用于 update 或任何方法

    //Added additional arg
    $.fn[pluginName] = function(option, mydata) {
    

    然后在调用部分,

    data[option](mydata);
    

    【讨论】: