addEventListener - 检测div元素的变化?

时间:2016-04-11 23:35:55

标签: javascript

我想检测div元素的变化。我已经尝试了" addEventListener"某些类型(例如:更改,加载)。

这是我的例子,但事件不会触发:

<!doctype html>
<html>
    <head>
    </head>
    <body>
        <div id='DivElement'>Test Div Text...</div>
        <button type="button" onclick="EditDivElement()">click me!</button>

        <script>
            function EditDivElement() {
                ClickCounter++;
                SelectedDiv.textContent="new text content: " + ClickCounter;
            }

            function OnDivEdit() {
                alert("success!");
            }

            var ClickCounter = 0;
            var SelectedDiv = document.querySelector("#DivElement");

            SelectedDiv.addEventListener("change", OnDivEdit);
        </script>
    </body>
</html>

(编辑:它适用于浏览器插件,应该在其他网站上使用。)

1 个答案:

答案 0 :(得分:2)

您可以使用MutationObserver

来自MDN:

// select the target node
var target = document.querySelector('#some-id');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });    
});

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

注意:已弃用

我在写的扩展中所做的就是听DOMNodeInserted

div.addEventListener("DOMNodeInserted", function (e) {
    e.target // 
}, false);