JavaScript 中的简单变异观察器示例不起作用
Simple mutation observer example in JavaScript doesn't work
我尝试在我的网页中添加一个 MutationObserver
来跟踪图像 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
方法,您将不会再收到通知:
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">
我尝试在我的网页中添加一个 MutationObserver
来跟踪图像 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
方法,您将不会再收到通知:
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">