MutationObserver 在 innerText 改变时不会被触发。

huangapple go评论55阅读模式
英文:

MutationObserver is not triggered when innerText changes

问题

我正在运行一个JavaScript文件在这个URL上。我对红色轮廓的元素的变化很感兴趣:

MutationObserver 在 innerText 改变时不会被触发。

我写了以下脚本

const $xpath = xp => {
  const snapshot = document.evaluate(
    xp, document, null,
    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null
  );
  return [...Array(snapshot.snapshotLength)]
    .map((_, i) => snapshot.snapshotItem(i));
};

const xpathOdds = './/div[@col-id="bestOdds"]/descendant::div[@class="d-flex justify-content-between align-items-center"]';
var odds = $xpath(xpathOdds);
var config = {
  characterData: true,
  attributes: true,
  childList: true,
  subtree: true
};

odds.forEach(function(target, idx) {
  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        console.log(mutation);
    });
  });
  observer.observe(target, config);
})

我不确定为什么`MutationObserver`没有被触发。
如果*我*使用鼠标右键点击“检查”编辑元素,它会被触发。
但是,如果*网站本身*对相关元素进行更改,它不会被触发。
当元素发生变化时,它会变成黄色,所以我知道应该已经有变化。
我做错了什么?

<details>
<summary>英文:</summary>

I am running a JavaScript file on this [URL][1]. I am interested in changes in the *red* outlined elements:

[![enter image description here][2]][2]


I wrote the following script

    const $xpath = xp =&gt; {
      const snapshot = document.evaluate(
        xp, document, null,
        XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null
      );
      return [...Array(snapshot.snapshotLength)]
        .map((_, i) =&gt; snapshot.snapshotItem(i));
    };
  
    const xpathOdds = &#39;.//div[@col-id=&quot;bestOdds&quot;]/descendant::div[@class=&quot;d-flex justify-content-between align-items-center&quot;]&#39;;
    var odds = $xpath(xpathOdds);
    var config = {characterData: true,
                  attributes: true,
                  childList: true,
                  subtree: true
    };
    
    odds.forEach(function(target, idx) {
      var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            console.log(mutation);
        });
      });
      observer.observe(target, config);
    })

  [1]: https://labs.actionnetwork.com/markets?league=PGA
  [2]: https://i.stack.imgur.com/gaMNE.png

I am not sure why the `MutationObserver` is not triggered. 
It is triggered if *I* edit an element using right mouse click - &quot;Inspect&quot;. 
However, it is not triggered if *the website* itself makes changes to the elements in question.
When an element changes it becomes yellow, so I know there should have been mutations.
What am I doing wrong? 


</details>


# 答案1
**得分**: 3

我检查了你发布的链接,我认为问题在于你将观察者附加到错误的对象上。问题在于,当发生更新并且单元格的颜色变成黄色时,整个表格都被替换了,而不仅仅是单元格。因此,你之前观察的单元格已经不存在了,无法被观察到。你应该将观察者附加到不会被替换的更高层次的元素,比如具有类`ag-center-cols-viewport`的元素,或者直接附加到文档本身。

<details>
<summary>英文:</summary>

I checked the link you posted, and I think the problem is you are attaching the observers to the wrong objects. The thing is, when there is an update and the color of the cell becomes yellow, the whole table get replaced and not just the cells. So the cells you were observing are no longer there to be observed. You should attach the observer to a higher element in the hierarchy that does not get replaced, like that one with the class `ag-center-cols-viewport` or the document itself.



</details>



# 答案2
**得分**: 0

它可能与突变观察器的配置有关。

```javascript
var config = {
  attributes: true,
  childList: true,
  subtree: true, // 因为你正在观察一个子元素上所做的更改。
  characterData: true  // 你要查找的更改是在内容中而不是在元素级别。
};
英文:

It probably has to do with the config for mutation observer.

var config = {
  attributes: true,
  childList: true,
  subtree: true, // Because you&#39;re watching for changes made to one of the children element.
  characterData: true  // The changes you&#39;re looking for are in the content and not at element level.
});

答案3

得分: 0

你期望触发观察者的变化与元素的样式相关。您必须设置观察者以监视元素的属性变化,包括其所有样式属性。 attributeFilter: ['style']

var config = {
  attributes: true,
  attributeFilter: ['style'],
  childList: true,
  subtree: true
};
英文:

The changes you expect triggering the observer are related to the element's style. You have to set the the observer to monitor changes to the element's attributes, including all its style attributes.
attributeFilter: [&#39;style&#39;]

var config = {
  attributes: true,
  attributeFilter: [&#39;style&#39;],
  childList: true,
  subtree: true
};

答案4

得分: -1

可能是因为网站是使用Next.js和虚拟DOM渲染的,而mutationObserver不会对虚拟DOM上的更改作出反应。要检查使网站本身发生变化的更改,您可以使用其他方法。例如,使用setInterval。

最近我在这里看到类似的问题:https://stackoverflow.com/q/19541050/

英文:

Maybe its caused because site rendered using Next.js and Virtulal DOM. And mutationObserver doesnt react with changes on virtual dom.
And to check changes that make the site itself you can use some other way. For example with setInterval.

Something like this problem I viewed recently here https://stackoverflow.com/q/19541050/

huangapple
  • 本文由 发表于 2023年2月10日 02:55:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75403213.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定