监听元素变化的三种方法:html
有时须要给一个class类型的对象绑定某个事件,对于之后新插入的class类型的元素也要绑定这样的事件。jQuery中很好的实现了这一功能。实际上,只须要DOMNodeInserted和DOMNodeRemoved两个事件就能够监听元素增删,从而能够在增删元素以前,为元素绑定事件。node
DOMNodeInserted和DOMNodeRemoved两个事件所对应的方法是浏览器自动执行的,执行时机为真正增删元素以前。浏览器
其它的DOM mutation事件:app
详情参考MDNide
经过如下demo,操做并查看日志能够更好的理解这两个事件。
demo解释:有三个按钮,第一个按钮经过更改innerHTML来添加元素,第二个按钮经过建立元素并插入的方式来添加元素,第三个按钮用于删掉最后一个元素触发DOMNodeRemoved事件。
若是经过innerHTML添加元素,会首先触发不少次删除元素的操做,这样会有较大的建立、销毁对象开销,所以对于少许更改,尽可能少用innerHTML而是用建立元素的方式。对于大量更改,使用innerHTML更合理。ui
<html> <body> <div id="main"> <button onclick="addOne()">add one by html</button> <button onclick="add()">add one by element</button> <button onclick="removeOne()">remove one by element</button> </main> </body> <script> var main = document.querySelector("#main") function addOne() { console.log("add node by html") main.innerHTML += "<p>haha</p>"; console.log("added node") } function add() { console.log("adding node by element") var ele = document.createElement('p') ele.innerHTML = "haha" main.appendChild(ele) console.log("added node") } function removeOne() { var sons = main.children var removing = sons[sons.length - 1] console.log("removing " + removing.tagName) if (removing.tagName.toLowerCase() == 'button') { alert("别再remove了!") return } main.removeChild(removing) console.log("child removed") } document.body.addEventListener("DOMNodeInserted", function () { console.log('DOMNode inserted') console.log(arguments) }) document.body.addEventListener("DOMNodeRemoved", function () { console.log("DOMNode removed") console.log(arguments) }) </script> </html>