猿问

检测DOM中的更改

检测DOM中的更改

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

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


慕勒3428872
浏览 664回答 3
3回答

繁星点点滴滴

IE9+,FF,Webkit:使用突变观察员回到不受欢迎的地方突变事件如有需要:(下面的例子是,如果仅针对附加或删除节点的DOM更改)var observeDOM = (function(){&nbsp; var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;&nbsp; return function( obj, callback ){&nbsp; &nbsp; if( !obj || !obj.nodeType === 1 ) return; // validation&nbsp; &nbsp; if( MutationObserver ){&nbsp; &nbsp; &nbsp; // define a new observer&nbsp; &nbsp; &nbsp; var obs = new MutationObserver(function(mutations, observer){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; callback(mutations);&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; // have the observer observe foo for changes in children&nbsp; &nbsp; &nbsp; obs.observe( obj, { childList:true, subtree:true });&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; else if( window.addEventListener ){&nbsp; &nbsp; &nbsp; obj.addEventListener('DOMNodeInserted', callback, false);&nbsp; &nbsp; &nbsp; obj.addEventListener('DOMNodeRemoved', callback, false);&nbsp; &nbsp; }&nbsp; }})();//------------< DEMO BELOW >----------------// add itemvar itemHTML = "<li><button>list item (click to delete)</button></li>",&nbsp; &nbsp; listElm = document.querySelector('ol');document.querySelector('body > button').onclick = function(e){&nbsp; listElm.insertAdjacentHTML("beforeend", itemHTML);}// delete itemlistElm.onclick = function(e){&nbsp; if( e.target.nodeName == "BUTTON" )&nbsp; &nbsp; e.target.parentNode.parentNode.removeChild(e.target.parentNode);}&nbsp; &nbsp;&nbsp;// Observe a specific DOM element:observeDOM( listElm, function(m){&nbsp;&nbsp; &nbsp;var addedNodes = [], removedNodes = [];&nbsp; &nbsp;m.forEach(record => record.addedNodes.length & addedNodes.push(...record.addedNodes))&nbsp; &nbsp;&nbsp; &nbsp;m.forEach(record => record.removedNodes.length & removedNodes.push(...record.removedNodes))&nbsp; console.clear();&nbsp; console.log('Added:', addedNodes, 'Removed:', removedNodes);});// Insert 3 DOM nodes at once after 3 secondssetTimeout(function(){&nbsp; &nbsp;listElm.removeChild(listElm.lastElementChild);&nbsp; &nbsp;listElm.insertAdjacentHTML("beforeend", Array(4).join(itemHTML));}, 3000);<button>Add Item</button><ol>&nbsp; <li><button>list item (click to delete)</button></li>&nbsp; <li><button>list item (click to delete)</button></li>&nbsp; <li><button>list item (click to delete)</button></li>&nbsp; <li><button>list item (click to delete)</button></li>&nbsp; <li><em>&hellip;More will be added after 3 seconds&hellip;</em></li></ol>
随时随地看视频慕课网APP
我要回答