繁体   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?

我一直在尝试从 HTML 文档中记录更新的成本信息,但没有成功。 我确信一定是我没有正确使用突变观察器。 js文件已链接。 下面是我要定位的 HTML 元素。

HTML:

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

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);

如果进行更改的代码更改了您正在查看的文本节点而不是销毁和替换它,您的代码将起作用,如下所示:

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

现场示例:

 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>

但是进行更改的代码可能会破坏和替换子节点,如下所示:

total.innerText = "1.00";

为了解决这个问题,您最好注意观察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>

您可能需要对其进行改进(我删除了if仅检查characterData更改),和/或将其与您已有的内容结合起来(以防其他代码以不同方式更改文本),但这是您所拥有的主要问题。

暂无
暂无

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

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