【问题标题】:addEventListener - detect changes in div-elements?addEventListener - 检测 div 元素的变化?
【发布时间】:2016-04-11 23:35:55
【问题描述】:

我想检测 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>

(编辑:这是一个浏览器插件,应该在其他网站上使用。)

【问题讨论】:

  • 因为您是进行更改的人,所以您应该只使用您已经拥有的功能,因为侦听 DOM 更改(突变)通常不是一个好主意。
  • 这是一个浏览器插件,应该在其他网站上使用。

标签: javascript


【解决方案1】:

您可以使用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);

【讨论】:

  • 谢谢! MutationObserver 运行良好。还有你不推荐使用的函数。
猜你喜欢
  • 2014-06-28
  • 2021-05-18
  • 1970-01-01
  • 1970-01-01
  • 2019-08-12
  • 2012-11-14
  • 1970-01-01
  • 2010-11-08
  • 2019-10-31
相关资源
最近更新 更多