Javascript 如何拦截javascript中的innerHTML更改?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7381293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:03:23  来源:igfitidea点击:

how to intercept innerHTML changes in javascript?

javascriptaddeventlistenerinterception

提问by tic

I need to intercept any changes in the content of a cell inside my webpage.

我需要拦截网页内单元格内容的任何更改。

The following code shows me that addEventListener does not work.

以下代码显示 addEventListener 不起作用。

function modifyText() {
alert("!");
}

var el=document.getElementById("mycell");
el.innerHTML="a"
el.addEventListener("change", modifyText, false); 
// After next instruction I expect an alert message but it does not appear...
el.innerHTML="Z";

The code is just a toy example. In my real case the changes in the page (and therefore in the cell, too) are made by a webapp that I have NO control over.

该代码只是一个玩具示例。在我的真实案例中,页面中的更改(因此也在单元格中)是由我无法控制的 web 应用程序进行的。

采纳答案by Mohsen

You can't listen to a DOM element changethat way. changeevent is mostly for inputs

你不能那样听 DOM 元素changechange事件主要是为inputs

There is some other new DOM 3 events that would help you on this.

还有一些其他新的 DOM 3 事件可以帮助您解决这个问题。

Here is some:

这里有一些:

DOMCharacterDataModified//Draft

DOMCharacterDataModified//草稿

DOMSubtreeModified

DOMSubtreeModified

回答by Paul Grime

Does this Most efficient method of detecting/monitoring DOM changes?help?

是检测/监控 DOM 变化的最有效方法吗?帮助?

It seems like there aren't any 100% cross browser solutions, and one of the workarounds is to poll the elements of interest to see if their innerHTML.length changes!

似乎没有任何 100% 跨浏览器解决方案,一种解决方法是轮询感兴趣的元素以查看它们的 innerHTML.length 是否发生变化!

回答by legale

There is a modern way to catch innerhtml changes:

有一种现代方法可以捕获 innerhtml 的变化:

https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe

https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe

Example:

例子:

elementToObserve = window.document.getElementById('y-range').children[0];

// create a new instance of `MutationObserver` named `observer`, 
// passing it a callback function
observer = new MutationObserver(function(mutationsList, observer) {
    console.log(mutationsList);
});

// call `observe` on that MutationObserver instance, 
// passing it the element to observe, and the options object
observer.observe(elementToObserve, {characterData: false, childList: true, attributes: false});```

childList mutation fires on innerHTML change.