11

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

4

1 に答える 1

19

メソッドを呼び出すdisconnectと、通知を受信しなくなります。

MDN からの引用

disconnect()

MutationObserver インスタンスが DOM ミューテーションの通知を受信しないようにします。observe() メソッドが再度使用されるまで、オブザーバーのコールバックは呼び出されません。

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

于 2015-04-27T09:34:25.230 に答える