javascript - 使用 JQuery,是否可以在 DOM 元素调用 .remove() 时运行函数?

标签 javascript jquery html dom destructor

正如问题所述,我试图做的是有一个函数,当从 DOM 中删除 DOM 元素时调用该函数,就像析构函数一样。

我研究了卸载,但根据我的理解,只有当浏览器导航离开页面时才会调用它。

提前致谢!

最佳答案

可以使用 special events建立移除跟踪。我创建了an example允许绑定(bind)到 removed 事件。请注意,此方法仅在 jQuery 发起删除时有效(例如调用 $(…).remove())。对于更通用的解决方案,请使用 DOMNodeRemoved ,但这在 IE 中不起作用。

要启用对元素的跟踪,请调用 $(…).trackRemoval(),当您删除该元素或其父元素之一时,该元素将触发 removed 事件。

// Create a scope so that our variables are not global
(function(){
    /**
     * True while unbinding removal tracking
     */
    var isUntracking = false;

    /**
     * A reference that is only known here that nobody else can play with our special event.
     */
    var dummy = function(){};

    /**
     * Special event to track removals. This could have any name but is invoked during jQuery's cleanup on removal to detach event handlers.
     */
    jQuery.event.special.elementRemoved = {
        remove: function(o){
            if(o.handler===dummy && !isUntracking){
                $(this).trigger('removed');
            }
        }
    };

    /**
     * Starts removal tracking on an element
     */
    jQuery.fn.trackRemoval = function(){
        this.bind('elementRemoved', dummy);
    };

    /**
     * Stops removal tracking on an element
     */
    jQuery.fn.untrackRemoval = function(){
        isUntracking = true;
        this.unbind('elementRemoved', dummy);
        isUntracking = false;
    };
})();

jsFiddle包含使用示例代码。

关于javascript - 使用 JQuery,是否可以在 DOM 元素调用 .remove() 时运行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7685880/

相关文章:

javascript - 如何在JavaScript(angularjs)中根据不同的过滤条件显示新的网格数据

javascript - 点系统 - localStorage

html - 在输入字段中具有永久值,同时仍然能够向其中添加文本

javascript - 使用 jQuery 添加缓出效果

jquery - 具有背景图像问题的切换类

php - 使用 mysql 和 php 将动态创建的 div 数据发送到 html 模式

javascript - 如何在asp.net web表单应用程序中获取 'Enable CORS'?

javascript - angularjs view express 不允许 `+` ?

javascript - Django 和 Angular 2 错误 {dataService : undefined}

javascript - 引用错误 : event is not defined in mozila firefox