元素增删事件DOMNodeInserted和DOMNodeRemoved

监听元素变化的三种方法:

  • 对于表单类型的控件,使用onchange事件最好。
  • 使用DOMNodeInserted和DOMNodeRemoved事件
  • 使用定时器定时检测(下策)

有时需要给一个class类型的对象绑定某个事件,对于以后新插入的class类型的元素也要绑定这样的事件。jQuery中很好的实现了这一功能。实际上,只需要DOMNodeInserted和DOMNodeRemoved两个事件就可以监听元素增删,从而可以在增删元素之前,为元素绑定事件。

DOMNodeInserted和DOMNodeRemoved两个事件所对应的方法是浏览器自动执行的,执行时机为真正增删元素之前。

通过以下demo,操作并查看日志可以更好的理解这两个事件。
demo解释:有三个按钮,第一个按钮通过更改innerHTML来添加元素,第二个按钮通过创建元素并插入的方式来添加元素,第三个按钮用于删掉最后一个元素触发DOMNodeRemoved事件。
如果通过innerHTML添加元素,会首先触发很多次删除元素的操作,这样会有较大的创建、销毁对象开销,因此对于少量更改,尽量少用innerHTML而是用创建元素的方式。对于大量更改,使用innerHTML更合理。

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

猜你喜欢

转载自www.cnblogs.com/weiyinfu/p/11584047.html