【问题标题】:Overriding jQuery plugins init function覆盖 jQuery 插件的 init 函数
【发布时间】:2018-11-01 11:24:51
【问题描述】:

我想覆盖 jquery 插件的初始化函数和插件的自定义函数(例如 html)。但没有任何工作。这是我的代码

提前致谢。

(function(jQuery) {
  jQuery.mainplugin = function(element, options) {
    var defaults = {};

    this.init = function() {
      this.settings = jQuery.extend({}, defaults, options);
      alert('main')
      // more code here
    };

    this.html = function() {
      // main code here 
    }

    this.init();
  };

  jQuery.fn.mainplugin = function(options) {
    return this.each(function() {
      if (undefined == jQuery(this).data('mainplugin')) {
        var plugin = new jQuery.mainplugin(this, options);
        jQuery(this).data('mainplugin', plugin);
      }
    });
  };
})(jQuery);

这是我的覆盖代码:

$(document).ready(function($) {
  $.fn.mainplugin.init = function() {
    alert('override')
  }

  $.fn.mainplugin.html = function() {
    alert('override')
  }

  $(".is-wrapper").mainplugin();
});

【问题讨论】:

  • $(".is-wrapper").mainplugin({ init: function() { //自定义函数 } });像这样@RoryMcCrossan ??
  • 是的。我在下面添加了一个答案,给你一个完整的例子。

标签: jquery jquery-plugins overriding


【解决方案1】:

不要“覆盖”函数,而是通过options 对象将它们传递给插件:

(function($) {
  $.mainplugin = function(element, options) {
    var settings = $.extend({
      init: null,
      html: null
    }, options);

    this.init = settings.init || function() {
      console.log('main')
    };

    this.html = settings.html || function() {
      console.log('html');
    }

    this.init();
  };

  $.fn.mainplugin = function(options) {
    return this.each(function() {
      if (undefined == $(this).data('mainplugin')) {
        var plugin = new $.mainplugin(this, options);
        $(this).data('mainplugin', plugin);
      }
    });
  };
})(jQuery);

$(document).ready(function($) {
  // plain
  $('.foo').mainplugin().data('mainplugin').html();

  // overridden
  $(".is-wrapper").mainplugin({
    init: function() {
      console.log('init override');
    },
    html: function() {
      console.log('html override');
    }
  }).data('mainplugin').html();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo"></div>
<div class="is-wrapper"></div>

【讨论】:

  • 感谢@Rory,您的代码有效。但我原来的插件有上面例子中的代码。我看到你修改了主插件代码。如何在不修改主插件代码的情况下覆盖?
  • 如果您愿意,您可以使用与当前代码相同的模式,尽管您需要在扩展它之前访问选项,这将很难看。我上面使用的方法是jQuery plugin guide 的标准做法。
  • 但我当前的代码在这里不起作用。这就是我问的原因。我需要让无论如何工作。实际上,我现在并没有考虑代码标准。 $.fn.mainplugin.init = function() { alert('override') }
  • 如果你能再举一个例子,那将是很大的帮助。
猜你喜欢
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-22
  • 2011-05-31
相关资源
最近更新 更多