我正在使用 jquery 插件样板(可在此处获得)来创建 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>
我究竟做错了什么?