javascript - 我需要从网站中选择一个元素 "x",但该网站加载元素“x”太慢

标签 javascript html

我正在尝试从网站中选择一个表格元素,并且我正在使用 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/

相关文章:

html - CSS 中的事件类

javascript - react 传单和 react 传单绘制

javascript - 谷歌街景: Show markers within given radius

javascript - 对象 JavaScript,无法读取未定义的属性...之前已读取

javascript - 将 DIV 滚动到绝对定位元素下方

html - Bootstrap - 垂直对齐按钮

jquery - 使网页横幅响应

javascript - 在 CSS3 或 HTML5 中更改元素背景颜色的有效方法

javascript - 黑色 Canvas 代替图像

javascript - 如何判断代码是否在try catch block 下