检测DOM中的更改

时间:2010-07-10 15:21:08

标签: javascript dom mutation-events mutation-observers

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

例如,添加了文本输入,然后应该调用该函数。

9 个答案:

答案 0 :(得分:199)

到目前为止,这是最终的方法,代码最小:

IE9 +,FF,Webkit:

  

使用MutationObserver并回退到已弃用的版本   Mutation events如果需要:
  (以下示例仅适用于有关添加或删除节点的DOM更改)

var observeDOM = (function(){
  var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

  return function( obj, callback ){
    if( !obj || !obj.nodeType === 1 ) return; // validation

    if( MutationObserver ){
      // define a new observer
      var obs = new MutationObserver(function(mutations, observer){
          callback(mutations);
      })
      // have the observer observe foo for changes in children
      obs.observe( obj, { childList:true, subtree:true });
    }
    
    else if( window.addEventListener ){
      obj.addEventListener('DOMNodeInserted', callback, false);
      obj.addEventListener('DOMNodeRemoved', callback, false);
    }
  }
})();

//------------< DEMO BELOW >----------------
// add item
var itemHTML = "<li><button>list item (click to delete)</button></li>",
    listElm = document.querySelector('ol');

document.querySelector('body > button').onclick = function(e){
  listElm.insertAdjacentHTML("beforeend", itemHTML);
}

// delete item
listElm.onclick = function(e){
  if( e.target.nodeName == "BUTTON" )
    e.target.parentNode.parentNode.removeChild(e.target.parentNode);
}
    
// Observe a specific DOM element:
observeDOM( listElm, function(m){ 
   var addedNodes = [], removedNodes = [];

   m.forEach(record => record.addedNodes.length & addedNodes.push(...record.addedNodes))
   
   m.forEach(record => record.removedNodes.length & removedNodes.push(...record.removedNodes))

  console.clear();
  console.log('Added:', addedNodes, 'Removed:', removedNodes);
});


// Insert 3 DOM nodes at once after 3 seconds
setTimeout(function(){
   listElm.removeChild(listElm.lastElementChild);
   listElm.insertAdjacentHTML("beforeend", Array(4).join(itemHTML));
}, 3000);
<button>Add Item</button>
<ol>
  <li><button>list item (click to delete)</button></li>
  <li><button>list item (click to delete)</button></li>
  <li><button>list item (click to delete)</button></li>
  <li><button>list item (click to delete)</button></li>
  <li><em>&hellip;More will be added after 3 seconds&hellip;</em></li>
</ol>

答案 1 :(得分:176)

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

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

如果您需要支持旧版本,您可以尝试回归其他方法,例如下面 5 (!)年回答中提到的方法。有龙。享受:)


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

DOM Level-2有Mutation event types ,但旧版本的IE不支持它。请注意,突变事件为deprecated in the DOM3 Events spec并且具有performance penalty

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

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

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

我写了一个概念证明:

(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 +

答案 2 :(得分:14)

我最近编写了一个插件,它正是这样做的 - jquery.initialize

您使用与.each功能

相同的方式
$(".some-element").initialize( function(){
    $(this).css("color", "blue"); 
});

.each的区别在于 - 它需要你的选择器,在这种情况下为.some-element并且等待将来使用此选择器的新元素,如果添加这样的元素,它也将被初始化

在我们的案例中,初始化函数只是将元素颜色更改为蓝色。因此,如果我们添加新元素(无论是使用ajax还是F12检查员或其他任何东西),如:

$("<div/>").addClass('some-element').appendTo("body"); //new element will have blue color!

插件会立即启动它。插件也确保一个元素只初始化一次。因此,如果您添加元素,然后.detach()从主体添加它,然后再次添加它,它将不会再次初始化。

$("<div/>").addClass('some-element').appendTo("body").detach()
    .appendTo(".some-container");
//initialized only once

插件基于MutationObserver - 它可以在IE9和10上使用依赖关系,详见readme page

答案 3 :(得分:11)

或者您只需创建自己的活动即可随处运行

 $("body").on("domChanged", function () {
                //dom is changed 
            });


 $(".button").click(function () {

          //do some change
          $("button").append("<span>i am the new change</span>");

          //fire event
          $("body").trigger("domChanged");

        });

完整的例子 http://jsfiddle.net/hbmaam/Mq7NX/

答案 4 :(得分:4)

这是使用MutationObserver改编自Mozillablog post的示例

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

// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type == 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();

答案 5 :(得分:2)

使用MutationObserver界面,如Gabriele Romanato的blog

所示

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

// The node to be monitored
var target = $( "#content" )[0];

// Create an observer instance
var observer = new MutationObserver(function( mutations ) {
  mutations.forEach(function( mutation ) {
    var newNodes = mutation.addedNodes; // DOM NodeList
    if( newNodes !== null ) { // If there are new nodes added
        var $nodes = $( newNodes ); // jQuery set
        $nodes.each(function() {
            var $node = $( this );
            if( $node.hasClass( "message" ) ) {
                // do something
            }
        });
    }
  });    
});

// Configuration of the observer:
var config = { 
    attributes: true, 
    childList: true, 
    characterData: true 
};

// Pass in the target node, as well as the observer options
observer.observe(target, config);

// Later, you can stop observing
observer.disconnect();

答案 6 :(得分:1)

如何为此扩展jquery?

   (function () {
        var ev = new $.Event('remove'),
            orig = $.fn.remove;
        var evap = new $.Event('append'),
           origap = $.fn.append;
        $.fn.remove = function () {
            $(this).trigger(ev);
            return orig.apply(this, arguments);
        }
        $.fn.append = function () {
            $(this).trigger(evap);
            return origap.apply(this, arguments);
        }
    })();
    $(document).on('append', function (e) { /*write your logic here*/ });
    $(document).on('remove', function (e) { /*write your logic here*/ ) });

Jquery 1.9+已经为此建立了支持(我听说未经测试)。

答案 7 :(得分:0)

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations, observer) {
    // fired when a mutation occurs
    console.log(mutations, observer);
    // ...
});

// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
  subtree: true,
  attributes: true
  //...
});

完整的说明:https://stackoverflow.com/a/11546242/6569224

答案 8 :(得分:0)

使用 TrackChanges 检测 html 更改。 链接:https://www.npmjs.com/package/track-changes-js

示例

 let button = document.querySelector('.button');

 trackChanges.addObserver('buttonObserver', () => button);
 
 trackChanges.addHandler('buttonObserver', buttonHandler);

 function buttonHandler(button) {
   console.log(`Button created: ${button}`);
 }