【问题标题】:What is the new equivalent of DOMNodeInserted?DOMNodeInserted 的新等价物是什么?
【发布时间】:2016-11-01 16:19:37
【问题描述】:

DOMNodeInserted event has been deprecated 和所有突变事件已被突变观察者替换。

但是,within mutation observers 只有配置选项用于观察节点属性、内容和子节点的突变。与它在 DOM 树中的位置的变化无关。

我能想到的一个“解决方案”是观察从 document.body 开始的所有内容,搜索一个突变,即我的目标节点被添加,但这是一种非常糟糕的做任何事情的方式。

那么用 Mutation Observers 替换已弃用的 DOMNodeInserted 的预期方法是什么?

编辑:发现可能重复的What is the most efficient way of detecting when an element with a particular ID is inserted in the DOM

再一次,所以:The searchbar works better with Tags than Questions. Explaining this could reduce duplicates and save users time

下面是一些代码,您可以在其中看到所有可用的变异观察器配置选项都没有响应添加到页面的元素:

var addMe = document.createElement("div");
var config = {
  attributes: true,
  childList: true,
  characterData: true
}
var observer = new MutationObserver(function(mutations) {
  console.log(mutations);
});
observer.observe(addMe, config);

function appendAddMe() {
  document.body.appendChild(addMe);
}
div {
  height: 50px;
  width: 50px;
  background: #969;
}
<button onclick="appendAddMe()">Append addMe</button>

【问题讨论】:

    标签: javascript mutation-observers


    【解决方案1】:

    我真的不认为这是问题的答案,但我还是想分享它,因为它总比没有好。

    这个问题有一些很好的答案:What is the most efficient way of detecting when an element with a particular ID is inserted in the DOM

    特别是这个答案:https://stackoverflow.com/a/25107064/4808079 来自schettino72

    iframe 元素触发加载/卸载事件。您可以在要观看的元素中插入一个哑 iframe...并自己在原始元素中触发“加载”事件。

    function watch($ele){
        var $iframe = document.createElement('iframe');
        $iframe.style.display = 'none';
        $ele.appendChild($iframe);
        $iframe.addEventListener('load', function(){
          var event = new CustomEvent('load');
          $ele.dispatchEvent(event);
        });
    }
    

    我仍然希望保持这个问题的开放性,因为这是一个技巧,而不是一个真正的答案。 DOMNodeInserted 可能没有被弃用,所以每个人都可以这样做。

    【讨论】:

      猜你喜欢
      • 2016-05-06
      • 1970-01-01
      • 2014-05-08
      • 2014-06-12
      • 1970-01-01
      • 2022-11-28
      • 2015-09-01
      • 1970-01-01
      • 2018-07-10
      相关资源
      最近更新 更多