我正在使用jquery插件样板(available here)来创建div元素的扩展。该插件旨在添加原始div内的其他div或元素。我的问题是我希望能够破坏并重新创建div中的元素。
以下是插件代码的简化示例:
(function($) {
$.extension = function(element, options) {
var defaults = {
foo: 'bar',
onFoo: function() {}
}
var plugin = this;
plugin.settings = {}
var $element = $(element),
element = element;
plugin.init = function() {
plugin.settings = $.extend({}, defaults, options);
// code goes here
var newDiv = $(document.createElement("div"));
newDiv.html("hello world");
$element.append(newDiv);
}
plugin.foo_public_method = function() {
// code goes here
}
var foo_private_method = function() {
// code goes here
}
plugin.destroy = function () {
$element.empty();
}
plugin.init();
}
$.fn.extension = function(options) {
return this.each(function() {
if (undefined == $(this).data('extension')) {
var plugin = new $.extension(this, options);
$(this).data('extension', plugin);
}
});
}
})(jQuery);
正如您所看到的,我使用jquery empty()方法来擦除div的子节点。它擦除很好,但后来我无法重新创建它们。
以下是用于调用插件的html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="js/jquery1.7.2.min.js"> </script>
<script type="text/javascript" src="js/extension.js"> </script>
</head>
<body>
<button type="button" id="destroy">Destroy</button>
<button type="button" id="create">Create</button>
<div id="random" ></div>
<script>
$('#random').extension();
$('#destroy').click(function(){
$('#random').data('extension').destroy();
});
$('#create').click(function(){
alert("hey");
$('#random').extension();
});
</script>
</body>
</html>
我做错了什么?
答案 0 :(得分:1)
您没有删除旧数据,因此不会重新创建插件,因为它不会是== undefined
尝试
plugin.destroy = function () {
$element.empty().removeData("extension");
};