【问题标题】:Erasing and re-creating elements in jquery在 jquery 中擦除和重新创建元素
【发布时间】:2012-06-25 17:04:37
【问题描述】:

我正在使用 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>

我做错了什么?

【问题讨论】:

    标签: jquery boilerplate


    【解决方案1】:

    您没有删除旧数据,因此不会重新创建插件,因为它不会是 == undefined

    试试

    plugin.destroy = function () {
        $element.empty().removeData("extension");
    };
    

    【讨论】:

      猜你喜欢
      • 2017-11-04
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-27
      • 1970-01-01
      • 1970-01-01
      • 2014-08-17
      相关资源
      最近更新 更多