繁星点点滴滴
IE9+,FF,Webkit:使用突变观察员回到不受欢迎的地方突变事件如有需要:(下面的例子是,如果仅针对附加或删除节点的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 itemvar 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 itemlistElm.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 secondssetTimeout(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>…More will be added after 3 seconds…</em></li></ol>