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

如何将创建的HTML元素追加到另一个HTML文件中?

如何将创建的HTML元素追加到另一个HTML文件中?

你遇到的问题核心在于:当你点击按钮调用location.assign('2.html')时,当前的第一个HTML页面会被浏览器完全卸载,原来的JavaScript环境(包括你创建的elem元素、后续的条件判断代码)都会失效——因为新打开的2.html是一个全新的页面,它会重新加载JS文件,和之前的页面没有任何上下文关联。所以你原来写的if (location.pathname === '/2.html')其实是在旧页面跳转前执行的,这时候路径还没变成2.html,自然不会生效,就算生效了,旧页面的元素也带不到新页面里。

下面给你两种简单可行的解决方案:

方案一:通过URL参数传递内容

这种方法是在跳转时把需要的文本通过URL的查询参数传递给2.html,然后2.html加载时读取这个参数,自己创建元素并追加到main中。

修改共用的JS文件如下:

function myFunc() {
  // 先判断当前是否是第一个页面(有按钮的页面)
  const button1 = document.getElementById('1');
  const button2 = document.getElementById('2');
  if (button1 && button2) {
    button1.onclick = () => {
      // 跳转时带上text参数
      location.assign('2.html?text=1');
    }

    button2.onclick = () => {
      location.assign('2.html?text=2');
    }
  }

  // 判断当前是否是第二个页面(有main的页面)
  const main = document.getElementById('main');
  if (main && location.pathname === '/2.html') {
    // 读取URL中的查询参数
    const params = new URLSearchParams(location.search);
    const text = params.get('text');
    if (text) {
      const elem = document.createElement('h1');
      elem.textContent = text;
      main.appendChild(elem);
    }
  }
}

myFunc();

两个HTML文件的内容可以保持不变,只要2.html里有<main id="main"></main>并且引入了同一个JS文件就行。

方案二:通过localStorage临时存储内容

如果需要传递更复杂的数据,或者不想把内容暴露在URL里,可以用浏览器的localStorage临时存储文本,2.html加载后读取并显示,用完再清除。

修改JS文件如下:

function myFunc() {
  const button1 = document.getElementById('1');
  const button2 = document.getElementById('2');
  if (button1 && button2) {
    button1.onclick = () => {
      // 把文本存到localStorage
      localStorage.setItem('buttonText', '1');
      location.assign('2.html');
    }

    button2.onclick = () => {
      localStorage.setItem('buttonText', '2');
      location.assign('2.html');
    }
  }

  const main = document.getElementById('main');
  if (main && location.pathname === '/2.html') {
    // 读取localStorage中的内容
    const text = localStorage.getItem('buttonText');
    if (text) {
      const elem = document.createElement('h1');
      elem.textContent = text;
      main.appendChild(elem);
      // 用完后清除,避免下次打开2.html还显示旧内容
      localStorage.removeItem('buttonText');
    }
  }
}

myFunc();

这两种方案的核心都是把需要的内容传递到新页面,让新页面自己生成元素,因为页面跳转后上下文是完全独立的,没法直接从旧页面操作新页面的DOM。

备注:内容来源于stack exchange,提问作者Dejan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.15 09:50:30