我正在尝试从网站中选择一个表格元素,并且我正在使用 document.querySelectorAll() 来执行此操作。然而,我相信该网站正在从另一台服务器检索这些数据,并且需要一些时间。因此,当我尝试使用 querySelectorAll() 时,它显示为未定义。
我尝试添加一些事件监听器,例如 window.addEventListener("load")、document.addEventListener("DOMContentLoaded) 和 window.onload() = funciton()。
我认为这些事件监听器不起作用,因为从技术上讲,窗口/DOM 内容都已正式加载,但我需要的表只是稍后插入。有什么方法可以等待表加载以便我可以访问它吗?
最佳答案
您可以使用 mutation observer
监听代码运行时(在最坏的情况下,body
)时存在的元素的父级(或祖先)的 childList(可能还有子树)的更改,然后当观察者被调用时,检查元素 X。
实例:
// Example if you need to use an ancestor
const ob = new MutationObserver(records => {
const div = document.querySelector(".the-element");
if (div) {
ob.disconnect();
console.log("Got it");
}
});
ob.observe(
document.getElementById("ancestor"),
{
childList: true,
subtree: true // Only need this if it's an ancestor
}
);
// Simulates loading the element later
setTimeout(() => {
const div = document.createElement("div");
div.className = "the-element";
div.textContent = "I'm the element";
document.getElementById("parent").appendChild(div);
}, 800);
<div id="ancestor">
<div id="parent">
Parent
</div>
</div>
关于javascript - 我需要从网站中选择一个元素 "x",但该网站加载元素“x”太慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56778431/