如何从'document'以外的另一个HTML文件中查询Selector?

问题描述 投票:0回答:1

此代码:

 const mobileNavShow = document.querySelector('.mobile-nav-show');

只查看我项目的index.html,而我的navbar在navbar.html中并且超出了querySelector的范围。我使用 w3 的

w3-include-html
来链接两者。如果我将 navbar.html 的内容复制到 index.html 的正文中,我的导航栏将按预期工作。我不确定我所面临问题的技术术语。

我尝试在单独的 HTML 文件中创建导航栏,但 js“document.querySelector('X')”无法在其他 HTML 文件中找到元素。

javascript html
1个回答
0
投票

您需要等待这些html文件被加载并且

[w3-include-html]
s的innerHTML被替换。

使用

Promise.all()
加载并替换innerHTM,将主要js代码(例如:
const mobileNavShow = document.querySelector...
)放在
main.js
中,在
Promise.all()
之后导入。

const getHTML = async (elem, file) => {
  const html = await fetch(file).then((res) => res.text());
  elem.innerHTML = html;
};
const includeHTML = async () => {
  const elements = [...document.querySelectorAll("[w3-include-html]")].map((elem) => ({ elem, file: elem.getAttribute("w3-include-html") }));
  Promise.all(elements.map(({ elem, file }) => getHTML(elem, file)));
  await import("./main.js");
};
includeHTML();
© www.soinside.com 2019 - 2024. All rights reserved.