简体   繁体   English

我正在尝试使用 MutationObserver 检测特定元素的更改,但它不起作用。 我究竟做错了什么?

[英]I am trying to detect changes on a particular element using the MutationObserver but it is not working. What am I doing wrong?

I have been trying to log the updated cost information from an HTML document but have not been successful.我一直在尝试从 HTML 文档中记录更新的成本信息,但没有成功。 I am sure it has to be that I am not using the mutation observer correctly.我确信一定是我没有正确使用突变观察器。 The js file is linked. js文件已链接。 Below is the HTML element that I am targeting.下面是我要定位的 HTML 元素。

HTML: HTML:

<span id="cost">0.00</span>

The JS file contains the following code: JS 文件包含以下代码:


const total = document.getElementById('cost');

console.log(total);
const options = {
  characterData: true
};

function logCallback(mutations) {
  console.log('called');

  for (let mutation of mutations) {
    if (mutation.type === 'characterData')
    {
      console.log('Mutation Detected: Price changed');
    }
  }
}

const observer = new MutationObserver(logCallback);

observer.observe(total.childNodes[0], options);

Your code would work if the code that was making the change changed the text node you're watching rather than destroying and replacing it, like this:如果进行更改的代码更改了您正在查看的文本节点而不是销毁和替换它,您的代码将起作用,如下所示:

total.childNodes[0].nodeValue = "1.00";

Live Example:现场示例:

 const total = document.getElementById('cost'); const options = { characterData: true, }; function logCallback(mutations) { console.log('called'); for (let mutation of mutations) { if (mutation.type === 'characterData') { console.log('Mutation Detected: Price changed'); } } } const observer = new MutationObserver(logCallback); observer.observe(total.childNodes[0], options); // Code that changes the element total.childNodes[0].nodeValue = "1.00";
 <span id="cost">0.00</span>

But the code making the change is probably destroying and replacing the child node, like this:但是进行更改的代码可能会破坏和替换子节点,如下所示:

total.innerText = "1.00";

To handle that, you're probably best off watching for childList changes on the total element itself:为了解决这个问题,您最好注意观察total元素本身的childList变化:

 const total = document.getElementById('cost'); const options = { childList: true, }; function logCallback(mutations) { console.log('called'); for (let mutation of mutations) { console.log('Mutation Detected: Price changed'); } } const observer = new MutationObserver(logCallback); observer.observe(total, options); // Code that changes the element total.innerText = "1.00";
 <span id="cost">0.00</span>

You may need to refine that (I removed the if checking only for characterData changes), and/or combine it with what you already had (in case some other code changes the text differently), but that's the main issue with what you had.您可能需要对其进行改进(我删除了if仅检查characterData更改),和/或将其与您已有的内容结合起来(以防其他代码以不同方式更改文本),但这是您所拥有的主要问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM