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

发布于 2024-12-08 10:05:56 字数 115 浏览 2 评论 0原文

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

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

提前致谢!

As the question states, what I'm attempting to do is have a function that is called when a DOM element is removed from the DOM, much like a destructor.

I looked into unload, but from my understanding that's only called when the browser navigates away from the page.

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

预谋 2024-12-15 10:05:56

可以使用特殊事件 建立移除跟踪。我创建了一个示例,它允许绑定到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 包含使用示例代码。

It is possible to use the special events to build removal tracking. I've created an example that allows to bind to an removed event. Note that this approach only works when the removal is initiated by jQuery (calling $(…).remove()) for example. For a more general solution use DOMNodeRemoved but that wouldn't work in IE.

To enable tracking for an element call $(…).trackRemoval() and the element will fire a removed event when you remove it or one of its parents.

// 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;
    };
})();

The jsFiddle contains sample code for usage.

[旋木] 2024-12-15 10:05:56

我不知道这是不是你要找的。不是很漂亮的代码,只是为了展示我想使用的内容:

// Just for this script's sake, you'll want to do it differently
var body = $("body");
var element = $('#loadingBlock');

// Bind the "destructor" firing event
body.bind("elementDeleted", function (element) {
  // your "destructor" code
});

// Trigger the event, delete element, can be placed in a function, overloaded, etc.
body.trigger("elementDeleted", element);
element.remove();

当然有基于直接观察 DOM 的解决方案,但问题是浏览器兼容性。您可能应该查看 突变事件

I don't know if it's that what you're looking for. Not really pretty code, just to show what I would like to use:

// Just for this script's sake, you'll want to do it differently
var body = $("body");
var element = $('#loadingBlock');

// Bind the "destructor" firing event
body.bind("elementDeleted", function (element) {
  // your "destructor" code
});

// Trigger the event, delete element, can be placed in a function, overloaded, etc.
body.trigger("elementDeleted", element);
element.remove();

There are of course solutions based on watching the DOM directly but the problem is the browser compatibility. You should probably check out mutation events.

删除会话 2024-12-15 10:05:56

试试这个:

(function($) {
    var _remove = $.fn.remove;
    $.fn.remove = function() {
        this.trigger('remove');             // notify removal
        return _remove.apply(this, arguments); // call original
    };
})(jQuery);

用法:

$(element).bind('remove', callback);
...
// some time later
$(element).remove();

请参阅 http://jsfiddle.net/alnitak/25Pnn/ 的工作示例

Try this:

(function($) {
    var _remove = $.fn.remove;
    $.fn.remove = function() {
        this.trigger('remove');             // notify removal
        return _remove.apply(this, arguments); // call original
    };
})(jQuery);

usage:

$(element).bind('remove', callback);
...
// some time later
$(element).remove();

See a working example at http://jsfiddle.net/alnitak/25Pnn/

蹲在坟头点根烟 2024-12-15 10:05:56

您始终可以重载删除函数(所有 JavaScript 对象都可以在运行时动态更改)并将其替换为您自己的函数,该函数会触发一个事件,您可以使用该事件来响应删除。

You could always Overload the Remove function (all javascript objects can be dynamically changes in runtime) and replace it with your own function that triggers an event you can use to react to remove.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文