Simple mutation observer example in JavaScript doesn't work

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-23 07:31:15

问题


I try to add a MutationObserver in my web page to track changes in an image src, but that doesn't work.

Here's the code used:

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">

回答1:


If you call disconnect method you will not receive notification anymore:

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://stackoverflow.com/questions/29890937/simple-mutation-observer-example-in-javascript-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!