gpt4 book ai didi

javascript - addEventListener - 检测 div 元素的变化?

转载 作者:行者123 更新时间:2023-11-30 12:01:21 26 4
gpt4 key购买 nike

我想检测 div 元素的变化。我已经尝试了某些类型的“addEventListener”(例如:更改、加载)。

这是我的例子,但是事件不会触发:

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

(编辑:这是一个浏览器插件,应该在其他网站上使用。)

最佳答案

您可以使用 MutationObserver .

来自 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();

注意:已弃用

我在我编写的扩展中所做的是监听 DOMNodeInserted

div.addEventListener("DOMNodeInserted", function (e) {
e.target //
}, false);

关于javascript - addEventListener - 检测 div 元素的变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36561100/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com