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



我正在制作自己的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()
});

});

我想通了。我需要在销毁方法中添加它

$(this).removeData('plugin_' + pluginName);

最新更新