销毁后无法重新实例化jQuery插件

问题描述 投票:0回答:1

我正在制作自己的jquery插件,销毁后无法重新初始化该插件。为了清楚起见,我将代码简化为基本内容。我已经尝试了很多研究,但似乎每个人都以完全不同的方式来创建这些插件。我用作参考的样板在这里https://github.com/jquery-boilerplate/jquery-boilerplate/blob/master/src/jquery.boilerplate.js

当我单击初始化按钮时,文本变为红色。然后按销毁按钮使文本变黑。但是然后再次按下init不会使文本变为红色。

<div id="banner-message">
  <p>Hello World</p>
  <button class="init">init</button>
  <button class="destroy">destroy</button>
</div>

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

  "use strict";

  let pluginName = "myPlugin",
      defaults = {
        color: 'red',
      };

  function Plugin(element, options) {

    this.element = element;

    this.settings = $.extend({}, defaults, options);
    this._defaults = defaults;
    this._name = pluginName;

    this.wrapper = '';
    this.text = '';

    this.init();
  }


  $.extend(Plugin.prototype, {

    init: function () {
      let o = this.settings;

      this.wrapper = $(this.element);
      this.text = this.wrapper.find('p');

      this.text.css('color', o.color)
    },

  });

  $.fn.destroy = function() {
    return this.each(function () {

      let plugin = $.data(this, "plugin_" + pluginName);
      plugin.text.css('color', 'black')

    })

  };

  $.fn[pluginName] = function (options) {
    return this.each(function () {
      if (!$.data(this, "plugin_" + pluginName)) {
        $.data(this, "plugin_" +
               pluginName, new Plugin(this, options));
      }
    });
  };

})(jQuery, window, document);




$(document).ready(function () {

  let x = '';

  $(document).on("click", ".init", function () {
    x = $('#banner-message').myPlugin();
  });

  $(document).on("click", ".destroy", function () {
    x.destroy()
  });


});


jquery jquery-plugins
1个回答
0
投票

我知道了。我需要将其添加到destroy方法中

   $(this).removeData('plugin_' + pluginName);
© www.soinside.com 2019 - 2024. All rights reserved.