315

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

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

4

10 回答 10

262

迄今为止的终极方法,使用最少的代码:

(IE11+、FF、Webkit)

使用MutationObserver并在需要时回退到已弃用的 Mutation 事件:(
下面的示例仅适用于与附加或删除节点有关的 DOM 更改)

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

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

    if( MutationObserver ){
      // define a new observer
      var mutationObserver = new MutationObserver(callback)

      // have the observer observe foo for changes in children
      mutationObserver.observe( obj, { childList:true, subtree:true })
      return mutationObserver
    }
    
    // browser support fallback
    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>

于 2013-01-28T20:27:47.940 回答
242

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

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

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


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

DOM Level-2 有Mutation 事件类型,但旧版本的IE 不支持它。请注意,突变事件在 DOM3 事件规范中已被弃用,并且会降低性能

您可以尝试onpropertychange在 IE中模拟突变事件(如果它们都不可用,则回退到蛮力方法)。

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

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

我写了一个概念证明:

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

于 2010-07-10T15:24:28.247 回答
37

以下示例改编自 Mozilla Hacks 的博客文章,并使用了MutationObserver

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

浏览器支持:Chrome 18+、Firefox 14+、IE 11+、Safari 6+

于 2018-05-23T17:04:38.283 回答
13

或者你可以简单地创建你自己的事件,在任何地方运行

 $("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/

于 2014-03-06T06:30:44.040 回答
13

我最近写了一个插件,正是这样做的 - 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 上运行,并在自述文件页面上有详细说明。

于 2015-02-06T16:02:56.683 回答
6
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

于 2020-11-23T10:48:22.003 回答
5

使用Gabriele Romanato 的博客中所示的MutationObserver接口

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();
于 2018-05-23T16:59:53.437 回答
3

为此扩展一个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+ 已经建立了对此的支持(我听说没有测试过)。

于 2017-02-13T09:24:21.270 回答
2

8 年后,这是我使用的解决MutationObserver方案RxJS

observeDOMChange(document.querySelector('#dom-changes-here'))
  .subscribe(val => log('DOM-change detected'));

与其他方法的主要区别在于,CustomEvent当 DOM 发生变化时触发一个事件,并通过以下特性监听去抖动的事件以有效地执行用户逻辑;

  • 去抖动连续的 DOM 更改以防止执行过多
  • 在给定时间后停止观看
  • 停止观看 DOM 更改后删除事件侦听器/订阅者
  • 用于观察框架中发生的 DOM 变化,例如 Angular
import { fromEvent, timer} from 'rxjs';
import { debounceTime, takeUntil, tap } from 'rxjs/operators';

function observeDOMChange(el, options={}) {
  options = Object.assign({debounce: 100, expires: 2000}, options);

  const observer = new MutationObserver(list =>  {
    el.dispatchEvent(new CustomEvent('dom-change', {detail: list}));
  });
  observer.observe(el, {attributes: false, childList: true, subtree: true });

  let pipeFn;
  if (options.expires) {
    setTimeout(_ => observer.disconnect(), options.expires);
    pipeFn = takeUntil(timer(options.expires));
  } else {
    pipeFn = tap(_ => _); 
  }

  return fromEvent(el, 'dom-change')
    .pipe(pipeFn, debounceTime(options.debounce));
}

在 stackblitz 演示。
在此处输入图像描述

于 2021-10-02T03:30:12.433 回答
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}`);
 }
于 2021-07-16T12:40:50.557 回答