You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用HTML和JavaScript将.html页面内容插入到当前页面?

问题排查与修正方案

1. 修复无效HTML结构

你的HTML中<nav>直接嵌套<li>标签不符合规范,<li>必须被<ul>或<ol>包裹。浏览器会自动修正这类错误DOM,可能导致按钮元素无法被正确获取。

修正后的HTML:

<span>
  <nav>
    <ul>
      <li><button class="route-button" id="button-1">Page 1</button></li>
      <li><button class="route-button" id="button-2">Page 2</button></li>
      <li><button class="route-diver"><a href="./divertidos.html" alt="Scripts divertidos (con los que practico)">Divertidos 😂</a></button></li>
    </ul>
  </nav>
</span>

2. 确保JS在DOM加载完成后执行

如果JS代码放在<head>中,会在DOM元素渲染前执行,导致无法获取按钮和main元素。解决方式二选一:

  • 将JS代码放在<body>标签末尾;
  • 用DOMContentLoaded事件包裹代码(推荐):
document.addEventListener('DOMContentLoaded', () => {
  const button1 = document.getElementById('button-1');
  const button2 = document.getElementById('button-2');
  const mainElement = document.querySelector('main');

  button1.addEventListener('click', () => {
    fetch('./page1.html')
      .then(response => {
        // 校验请求是否成功
        if (!response.ok) throw new Error(`请求失败:${response.status}`);
        return response.text();
      })
      .then(html => {
        mainElement.innerHTML = html;
      })
      .catch(err => console.error('加载Page1失败:', err));
  });

  button2.addEventListener('click', () => {
    fetch('./page2.html')
      .then(response => {
        if (!response.ok) throw new Error(`请求失败:${response.status}`);
        return response.text();
      })
      .then(html => {
        mainElement.innerHTML = html;
      })
      .catch(err => console.error('加载Page2失败:', err));
  });
});

3. 验证文件路径正确性

确认page1.html和page2.html与当前HTML文件在同一目录下,若不在则调整fetch路径(例如./pages/page1.html)。

4. 检查main元素是否存在

确保页面中确实存在<main>标签,否则document.querySelector('main')会返回null,无法设置内容。


内容的提问来源于stack exchange,提问作者Lucas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 19:15:52