【问题标题】:MutationObserver - getting "TypeError: MutationObserver.observe: Argument 1 does not implement interface Node."MutationObserver - 得到“TypeError: MutationObserver.observe: Argument 1 does not implement interface Node.”
【发布时间】:2021-01-25 16:30:02
【问题描述】:

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

得到“TypeError: MutationObserver.observe: Argument 1 does not implement interface Node.”

我检查了MutationObserver documentationits options。看到了

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

我将属性设置为 true,但仍然收到 typeError

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

【问题讨论】:

  • jQuery 对象不是预期的参数,试试var changingContainer = $('.soliloquy-viewport').get(0)
  • @RoryMcCrossan :谢谢,混淆了.eq().get(),我已经很久没有使用jQuery了

标签: javascript jquery mutation-observers


【解决方案1】:

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

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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-28
    • 2019-12-02
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 2021-09-24
    相关资源
    最近更新 更多