"parameter 1 is not of type 'Node'" 使用 MutationObserver 时

"parameter 1 is not of type 'Node'" when using MutationObserver

我完全是 JS 菜鸟(以及一般的 Web 开发):(

目前,我正在为 Tampermonkey 编写一个小脚本,它负责管理特定 class 中的特定元素,并在元素发生任何变化时播放声音。 (值变化,元素hides/shows等)。

目前,我有以下代码:

     var audio = new Audio('URL_to_the_sound');
        var mutationObserver = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        console.log(mutation);
          audio.play();
      });
    });
    var target = document.getElementsByClassName('CLASSNAME');
        mutationObserver.observe(target, {
      attributes: true,
      characterData: true,
      childList: true,
      subtree: true,
      attributeOldValue: true,
      characterDataOldValue: true
    });

但是,我的浏览器响应以下错误:

Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.

我应该提到在同一个 class 中有几个元素。

我该怎么办? :(

您需要遍历 getElementsByClassName 返回的每个元素。这个方法 returns HTMLCollection 没有任何类似循环的方法,但是你可以把它转换成 A​​rray,然后使用 forEach 方法:

var targets = document.getElementsByClassName("CLASSNAME");

Array.from(targets).forEach(target => {
  mutationObserver.observe(target, {
    attributes: true,
    characterData: true,
    childList: true,
    subtree: true,
    attributeOldValue: true,
    characterDataOldValue: true
  });
});

这是基于您的代码片段的工作示例: https://stackblitz.com/edit/js-qbetr2

好的。我想到了。 我使用了以下功能:

waitForKeyElements (
            "span.classname"
            , soundfx, false
        );

它工作得还不错,我会尝试一下以获得更好的结果。 感谢所有对此 post 发表评论的人! :)