MutationObserver - 得到“类型错误:MutationObserver.observe:参数 1 没有实现接口节点”

问题描述

我正在尝试检测由图像滑块插件动态设置的元素的高度,并使用它来设置容器的高度。

得到“TypeError: MutationObserver.observe: Argument 1 没有实现接口节点。”

我检查了 MutationObserver documentationits options。看到了

调用observe() 时,至少,childList、attributes 和/或characterData 之一必须为真。否则会抛出 TypeError 异常。

并且我将属性设置为 true 但仍然得到 typeError

}//End TabView
      .accentColor(Color("ColorMainDark"))
        .id(appState.currentTab) //<--Here
jQuery(document).ready(function($){
  // Callback function to execute when mutations are observed
  const callback = function(mutationsList,observer) {
      for(const mutation of mutationsList) {
          console.log('The ' + mutation.attributeName + ' attribute was modified.');
      }
  };

  const observer = new MutationObserver(callback);

  //set up your configuration
  const config = { attributes:true,subtree: false };

  var changingContainer = $('.soliloquy-viewport');

  //start observing
  observer.observe(changingContainer,config);
  
  //change height on button press
  function changeHeight(){
    changingContainer.height(Math.floor((Math.random() * 100) + 20));
  }
  $("#height").click(changeHeight);
});
.soliloquy-viewport{
  background: yellow;
}

解决方法

MutationObervers 仅适用于 Element 对象,而不适用于 jQuery 对象。使用 observe()get() 的第一个参数更改为基础元素,如下所示:

observer.observe(changingContainer.get(0),config);

或者像这样通过索引访问 jQuery 对象:

observer.observe(changingContainer[0],config);

jQuery(document).ready(function($) {
  let $changingContainer = $('.soliloquy-viewport');
  
  const observer = new MutationObserver((ml,o) => {
    for (const m of ml) {
      console.log('The ' + m.attributeName + ' attribute was modified.');
    }
  });
  
  observer.observe($changingContainer.get(0),{
    attributes: true,subtree: false
  });

  //change height on button press
  $("#height").click(() => $changingContainer.height(Math.floor((Math.random() * 100) + 20)));
});
.soliloquy-viewport {
  background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<div class="soliloquy-viewport">Hello</div>
<button id="height">change height</button>

请注意,这仅适用于单个元素。对于具有相同类的多个元素,您需要遍历它们并单独应用 MO。