Javascript 为什么 DOMSubtreeModified 事件在 DOM 级别 3 中被弃用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6659662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:40:47  来源:igfitidea点击:

Why is the DOMSubtreeModified event deprecated in DOM level 3?

javascriptdomjavascript-eventsdeprecateddom3

提问by huyz

Why is the DOMSubtreeModified event deprecatedand what are we supposed to use instead?

为什么不推荐使用DOMSubtreeModified 事件,我们应该改用什么?

采纳答案by Domenic

If you scroll down a bit, you see:

如果你向下滚动一点,你会看到:

Warning! The MutationEventinterface was introduced in DOM Level 2 Events, but has not yet been completely and interoperably implemented across user agents. In addition, there have been critiques that the interface, as designed, introduces a performance and implementation challenge. A new specification is under development with the aim of addressing the use cases that mutation events solves, but in more performant manner. Thus, this specification describes mutation events for reference and completeness of legacy behavior, but deprecates the use of both the MutationEventinterface and the MutationNameEventinterface.

警告!该MutationEvent接口是在 DOM Level 2 Events 中引入的,但尚未在用户代理之间完全且互操作地实现。此外,也有人批评该界面的设计带来了性能和实现方面的挑战。一个新的规范正在开发中,旨在解决突变事件解决的用例,但以更高效的方式。因此,本规范描述了变异事件以供参考和遗留行为的完整性,但不赞成使用MutationEvent接口和MutationNameEvent接口。

The replacement API is mutation observers, which are fully specified in the DOM Living Standardthat supercedes all of the DOM level X silliness.

替代 API 是突变观察者,它在 DOM 生活标准中完全指定,取代了所有的 DOM 级别 X 愚蠢。

回答by ralfthewise

I think the replacement will be mutation observers: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

我认为替代者将是突变观察者:https: //developer.mozilla.org/en-US/docs/Web/API/MutationObserver

var whatToObserve = {childList: true, attributes: true, subtree: true, attributeOldValue: true, attributeFilter: ['class', 'style']};
var mutationObserver = new MutationObserver(function(mutationRecords) {
  $.each(mutationRecords, function(index, mutationRecord) {
    if (mutationRecord.type === 'childList') {
      if (mutationRecord.addedNodes.length > 0) {
        //DOM node added, do something
      }
      else if (mutationRecord.removedNodes.length > 0) {
        //DOM node removed, do something
      }
    }
    else if (mutationRecord.type === 'attributes') {
      if (mutationRecord.attributeName === 'class') {
        //class changed, do something
      }
    }
  });
});
mutationObserver.observe(document.body, whatToObserve);