检测 DOM 中的变化 [英] Detect changes in the DOM

查看:30
本文介绍了检测 DOM 中的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在将某些 div 或输入添加到 html 时执行一个函数.这可能吗?

I want to execute a function when some div or input are added to the html. Is this possible?

比如添加了一个文本输入,那么应该调用该函数.

For example, a text input is added, then the function should be called.

推荐答案

2015 更新,新的 MutationObserver 被现代浏览器支持:

Chrome 18+、Firefox 14+、IE 11+、Safari 6+

如果您需要支持较旧的方法,您可以尝试使用其他方法,例如下面这个 5 (!) 岁的答案中提到的方法.有龙.享受:)

If you need to support older ones, you may try to fall back to other approaches like the ones mentioned in this 5 (!) year old answer below. There be dragons. Enjoy :)

其他人正在更改文档?因为如果您可以完全控制更改,您只需要创建自己的 domChanged API - 使用函数或自定义事件 - 并在您修改内容的任何地方触发/调用它.

Someone else is changing the document? Because if you have full control over the changes you just need to create your own domChanged API - with a function or custom event - and trigger/call it everywhere you modify things.

DOM Level-2 具有 突变事件类型,但旧版本的 IE 不支持它.请注意,突变事件在 DOM3 事件规范中已弃用 并有 性能损失.

您可以尝试在 IE 中使用 onpropertychange 模拟突变事件(如果没有可用的方法,则退回到蛮力方法).

You can try to emulate mutation event with onpropertychange in IE (and fall back to the brute-force approach if non of them is available).

对于 full domChange,间隔可能会造成过度杀伤.想象一下,您需要存储整个文档的当前状态,并检查每个元素的每个属性是否相同.

For a full domChange an interval could be an over-kill. Imagine that you need to store the current state of the whole document, and examine every element's every property to be the same.

也许如果您只对元素及其顺序感兴趣(正如您在问题中提到的),getElementsByTagName("*") 可以工作.如果您添加元素、删除元素、替换元素或更改文档结构,这将自动触发.

Maybe if you're only interested in the elements and their order (as you mentioned in your question), a getElementsByTagName("*") can work. This will fire automatically if you add an element, remove an element, replace elements or change the structure of the document.

我写了一个概念证明:

(function (window) {
    var last = +new Date();
    var delay = 100; // default delay

    // Manage event queue
    var stack = [];

    function callback() {
        var now = +new Date();
        if (now - last > delay) {
            for (var i = 0; i < stack.length; i++) {
                stack[i]();
            }
            last = now;
        }
    }

    // Public interface
    var onDomChange = function (fn, newdelay) {
        if (newdelay) delay = newdelay;
        stack.push(fn);
    };

    // Naive approach for compatibility
    function naive() {

        var last = document.getElementsByTagName('*');
        var lastlen = last.length;
        var timer = setTimeout(function check() {

            // get current state of the document
            var current = document.getElementsByTagName('*');
            var len = current.length;

            // if the length is different
            // it's fairly obvious
            if (len != lastlen) {
                // just make sure the loop finishes early
                last = [];
            }

            // go check every element in order
            for (var i = 0; i < len; i++) {
                if (current[i] !== last[i]) {
                    callback();
                    last = current;
                    lastlen = len;
                    break;
                }
            }

            // over, and over, and over again
            setTimeout(check, delay);

        }, delay);
    }

    //
    //  Check for mutation events support
    //

    var support = {};

    var el = document.documentElement;
    var remain = 3;

    // callback for the tests
    function decide() {
        if (support.DOMNodeInserted) {
            window.addEventListener("DOMContentLoaded", function () {
                if (support.DOMSubtreeModified) { // for FF 3+, Chrome
                    el.addEventListener('DOMSubtreeModified', callback, false);
                } else { // for FF 2, Safari, Opera 9.6+
                    el.addEventListener('DOMNodeInserted', callback, false);
                    el.addEventListener('DOMNodeRemoved', callback, false);
                }
            }, false);
        } else if (document.onpropertychange) { // for IE 5.5+
            document.onpropertychange = callback;
        } else { // fallback
            naive();
        }
    }

    // checks a particular event
    function test(event) {
        el.addEventListener(event, function fn() {
            support[event] = true;
            el.removeEventListener(event, fn, false);
            if (--remain === 0) decide();
        }, false);
    }

    // attach test events
    if (window.addEventListener) {
        test('DOMSubtreeModified');
        test('DOMNodeInserted');
        test('DOMNodeRemoved');
    } else {
        decide();
    }

    // do the dummy test
    var dummy = document.createElement("div");
    el.appendChild(dummy);
    el.removeChild(dummy);

    // expose
    window.onDomChange = onDomChange;
})(window);

用法:

onDomChange(function(){ 
    alert("The Times They Are a-Changin'");
});

这适用于 IE 5.5+、FF 2+、Chrome、Safari 3+ 和 Opera 9.6+

This works on IE 5.5+, FF 2+, Chrome, Safari 3+ and Opera 9.6+

这篇关于检测 DOM 中的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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