JavaScript中的简单变异观察器示例不起作用

前端之家收集整理的这篇文章主要介绍了JavaScript中的简单变异观察器示例不起作用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我尝试在我的网页中添加MutationObserver以获取img src中的更改,但这不起作用.

这是使用的代码

setTimeout(function() {
  document.getElementById("img").src = "http://i.stack.imgur.com/aQsv7.jpg"
},2000);

var target = document.querySelector('#img');

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });
});

var config = {
  attributes: true,childList: false,characterData: false
};

observer.observe(target,config);
observer.disconnect();
<img src="http://i.stack.imgur.com/k7HT5.jpg" id="img" class="pic" height="100">

解决方法

如果您调用disconnect方法,则不会再收到通知

Quote from MDN

disconnect()

Stops the MutationObserver instance from receiving notifications of
DOM mutations. Until the observe() method is used again,observer’s
callback will not be invoked.

setTimeout(function() {
  document.getElementById("img").src = "http://i.stack.imgur.com/aQsv7.jpg"
},2000);

setTimeout(function() {
      document.getElementById("img").src = "http://i.imgur.com/Xw6htaT.jpg"
    },4000);

var target = document.querySelector('#img');

var observer = new MutationObserver(function(mutations) {
  
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });
});

var config = {
  attributes: true,childList: true,characterData: true
};

observer.observe(target,config);

// otherwise
observer.disconnect();
observer.observe(target,config);
<img src="http://i.stack.imgur.com/k7HT5.jpg" id="img" class="pic" height="100">
原文链接:https://www.f2er.com/js/158635.html

猜你在找的JavaScript相关文章