gpt4 book ai didi

javascript - 监听 HTML 元素,无需 setInterval

转载 作者:行者123 更新时间:2023-11-28 14:27:35 24 4
gpt4 key购买 nike

我想知道是否可以在不使用 setInterval 的情况下监听 DOM 中的元素,就像我现在正在做的那样:

var interval = setInterval(() => {
var div = document.querySelector('.test');
if (div != null) {
clearInterval(interval);
console.log(div);
}
}, 1000);

我的问题是这个特定的 div 在 10-12 分钟后随机加载到 DOM 中。我认为 setInterval 我只是一个丑陋的解决方案。所以我的问题是,是否有可能在不使用间隔的情况下监听 DOM 中的新 div?

最佳答案

这对于 Mutation Observer 来说似乎是一份不错的工作。它将观察 DOM 上的静态父级,并提醒您结构的任何更改。您可以监听要添加的类为 test 的子节点。例如:

// this setTimeout is only to show this example working. it is not needed 
setTimeout(() => {
let aDiv = document.createElement('div');
aDiv.className = 'test';
document.getElementById('parent').appendChild(aDiv);
}, 3000);

let targetNode = document.getElementById('parent');

let config = {
attributes: false,
childList: true,
subtree: true
};

// Callback function to execute when mutations are observed
let callback = function(mutationsList, observer) {
for (let mutation of mutationsList) {
if (mutation.type == 'childList') {
for (let node of mutation.addedNodes) {
if (node.className === "test") {
console.log("a node with class test was added!");
// stop observing
observer.disconnect();
}
}
}
}
};

// Create an observer instance linked to the callback function
let observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);
<div id="parent">

</div>

关于javascript - 监听 HTML 元素,无需 setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52634621/

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