prototype - 从DOM中删除元素时的触发事件 [英] prototype - Trigger event when an element is removed from the DOM

查看:75
本文介绍了prototype - 从DOM中删除元素时的触发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图弄清楚当从页面中删除元素时如何执行一些js代码:

I'm trying to figure out how to execute some js code when an element is removed from the page:

原型中的东西如:

$('custom-div').observe('remove', function(event) {
    // Handle the event
});

这样的事情是否存在?

推荐答案

在现代浏览器中,您可以使用 MutationObserver 。这里的代码将在从当前位置移除DOM元素时调用回调:

In modern browsers, you can use a MutationObserver. Here's code that will call a callback when a DOM element is removed from it's current location:

function watchRemove(el, fn) {
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            var item;
            if (mutation.type === "childList" && mutation.removedNodes) {
                for (var i = 0; i < mutation.removedNodes.length; i++) {
                    item = mutation.removedNodes[i];
                    if (item === el) {
                        // clear the observer
                        observer.disconnect();
                        fn.call(item, item);
                        break;
                    }
                }
            }
      });    
    });
    observer.observe(el.parentNode, {childList: true});
    return observer;
}

并且,一个有效的演示: http://jsfiddle.net/jfriend00/naft3qeb/

And, a working demo: http://jsfiddle.net/jfriend00/naft3qeb/

这会监视父母的如果传入的特定DOM元素被删除,则更改其直接子节点并调用回调。

This watches the parent for changes to its direct children and calls the callback if the specific DOM element passed in is removed.

观察者将在删除DOM元素时删除自身或 watchRemove()返回观察者实例,您可以随时调用 .disconnect()来停止观看。

The observer will remove itself when the DOM element is removed or watchRemove() returns the observer instance which you can call .disconnect() on at any time to stop the watching.

这是一个使用此功能的jQuery插件:

Here's a jQuery plug-in that uses this functionality:

jQuery.fn.watchRemove = function(fn, observers) {
    return this.each(function() {
        var o = watchRemove(this, fn);
        if (observers) {
            observers.push(o);
        }
    });
}

在这种情况下,它接受一个可选的数组对象作为参数将是填充了所有观察者对象(如果您希望能够在任何给定项目上停止观看,则只需要传递此对象)。

In this case, it accepts an optional array object as an argument that will be filled with all the observer objects (only necessary to pass this if you want to be able to stop the watching yourself on any given item).

这篇关于prototype - 从DOM中删除元素时的触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆