首页 > 解决方案 > JavaScript 变异观察者

问题描述

我正在尝试使用 Mutation Observer。我使用配置:

config = { characterData: true, characterDataOldValue: true };

我的html页面:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <script src="script.js"></script>
        <title>Test</title>
</head>
<body>
    <p id="test" contenteditable="true">Test<b>subtree</b>test</p>

在我将子树放入配置之前,突变观察者无法工作:

config = { characterData: true, subtree: true, characterDataOldValue: true };

谁能解释为什么?我不明白。

标签: javascript

解决方案


下面是变异观察者的代码,它工作正常。您能否显示更多代码,以便找出问题所在。有关更多信息,您必须参考这个 DOM MutationObserver - 在不影响浏览器性能的情况下对 DOM 更改做出反应。

const targetNode = document.getElementById('test');
console.log(targetNode);

// Create an observer instance linked to the callback function
const observer = new MutationObserver((mutationList,observer)=>{
  console.log("working");
});

// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
//observer.disconnect();
<p id="test" contenteditable="true">Test</p>


推荐阅读