Javascript addEventListener-检测div元素中的更改?
我想检测div元素中的变化。我已经尝试了一些类型的“addEventListener”(例如:change、load) 以下是我的示例,但事件不会触发:Javascript addEventListener-检测div元素中的更改?,javascript,Javascript,我想检测div元素中的变化。我已经尝试了一些类型的“addEventListener”(例如:change、load) 以下是我的示例,但事件不会触发: <!doctype html> <html> <head> </head> <body> <div id='DivElement'>Test Div Text...</div> <button typ
<!doctype html>
<html>
<head>
</head>
<body>
<div id='DivElement'>Test Div Text...</div>
<button type="button" onclick="EditDivElement()">click me!</button>
<script>
function EditDivElement() {
ClickCounter++;
SelectedDiv.textContent="new text content: " + ClickCounter;
}
function OnDivEdit() {
alert("success!");
}
var ClickCounter = 0;
var SelectedDiv = document.querySelector("#DivElement");
SelectedDiv.addEventListener("change", OnDivEdit);
</script>
</body>
</html>
测试Div文本。。。
点击我!
函数EditDivElement(){
单击计数器++;
选择ddiv.textContent=“新建文本内容:”+单击计数器;
}
函数OnDivEdit(){
警惕(“成功!”);
}
var-ClickCounter=0;
var SelectedDiv=document.querySelector(“#DivElement”);
选择AddeDiv.addEventListener(“更改”,OnDiveEdit);
(编辑:它用于浏览器插件,应该在其他网站上使用。)您可以使用 来自MDN:
// 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();
注:已弃用 在我编写的扩展中,我所做的是监听
domanodeinserted
div.addEventListener("DOMNodeInserted", function (e) {
e.target //
}, false);
由于您是进行更改的人,您应该直接连接到您已经拥有的功能,因为侦听DOM更改(突变)通常不是一个好主意。这是针对浏览器插件的,应该在其他网站上使用。可能是这样吗?非常感谢。MutationObserver工作得很好。还有你不推荐的函数。