Javascript:mutationobserver没有提醒消息

时间:2016-03-23 08:22:08

标签: javascript mutation-observers

我正在尝试检测元素中的CSS属性更改。我在网上搜索了MutationObserver javascript API。但在我的测试脚本中它没有按预期工作(它没有提醒属性名称和属性值)。

var foo = document.getElementById("hideit");

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    alert('mutation.type = ' + mutation.type);

  });

});
observer.observe(foo);
observer.disconnect();

$(function() {
  $("#clickhere").on("click", function() {
    $("#hideit").slideToggle('fase');
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

<body>
  <div id="clickhere">click to toggel</div>
  <div id="hideit" style="display:none;">this is the content of the hide/show toggle</div>

</body>

并显示javascript错误

TypeError: Argument 1 of MutationObserver.observe is not an object.

谢谢是提前

2 个答案:

答案 0 :(得分:4)

您的代码在实际加载DOM之前正在执行...因此,您将null / undefined值传递给myImageList.Images.Add(Properties.Resources.Employees);方法。

将您的代码包装在内:

observe

同时调用disconnect会阻止它接收任何事件。因此,在致电$( document ).ready(function() { .... }) 后,您不应该立即致电disconnect。并且您错过了observe来电的参数。

点击此处查看工作示例:

https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver#Example_usage

答案 1 :(得分:3)

您的代码中存在2个问题:

  1. observer.observe的使用不正确。它应该需要2个参数:节点和MutationObserverInit。查看正确的API here
  2. 请勿在{{1​​}}后立即致电observer.disconnect();Disconnect停止观察。
  3. Working example