我正在开发一个小型的 chrome 扩展来娱乐,我需要它能够做的一件事是检测 div 内的文本何时被网页本身更改。我使用的代码是:
var status = document.getElementById("status").innerHTML;
status.onchange = function() {
console.log("CHANGE DETECTED")
这似乎不起作用,那么我应该使用什么来代替?
注意:我不想使用 jquery,因为我现在还不太精通 javascript,但如果它能更简单/更容易,那就太好了。
最佳答案
使用这个技巧
// select the target node
var target = document.querySelector('#some-id');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.type);
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true }
// pass in the target node, as well as the observer options
observer.observe(target, config);
// later, you can stop observing
observer.disconnect();
关于javascript - 检测 JavaScript 中的 div 变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29405279/