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

如何用JavaScript将Index.html中<div>内容显示到Users.html的<div>中

实现方法

因为是两个独立的HTML页面,得先把Index.html里的内容存起来,再在Users.html里读取并显示,下面是两种简单的实现方式(前提是两个页面在同一域名下):

方法一:使用 localStorage 存储数据

步骤1:修改 Index.html,添加按钮点击事件

给导出按钮绑定点击事件,把source的内容存入localStorage,然后跳转到Users.html:

<div id="source">
    Contenido de Usuario
</div>

<input type="button" id="export" value="Export Data">

<script>
document.getElementById('export').addEventListener('click', function() {
    // 获取source的内容
    const sourceContent = document.getElementById('source').textContent.trim();
    // 存入localStorage
    localStorage.setItem('userContent', sourceContent);
    // 跳转到Users页面
    window.location.href = 'Users.html';
});
</script>

步骤2:修改 Users.html,读取 localStorage 并显示

在Users.html里读取刚才存的内容,插入到target容器里:

<div id="target">
</div>

<script>
window.onload = function() {
    // 读取localStorage里的内容
    const content = localStorage.getItem('userContent');
    if (content) {
        // 插入到target容器
        document.getElementById('target').textContent = content;
        // 可选:用完后删除存储的内容,避免下次打开还显示
        localStorage.removeItem('userContent');
    }
};
</script>

方法二:使用 URL 参数传递数据

步骤1:修改 Index.html,通过URL传递内容

点击按钮时把内容作为URL参数拼接,然后跳转:

<div id="source">
    Contenido de Usuario
</div>

<input type="button" id="export" value="Export Data">

<script>
document.getElementById('export').addEventListener('click', function() {
    const sourceContent = document.getElementById('source').textContent.trim();
    // 对内容进行编码,避免特殊字符问题
    const encodedContent = encodeURIComponent(sourceContent);
    // 拼接URL并跳转
    window.location.href = `Users.html?content=${encodedContent}`;
});
</script>

步骤2:修改 Users.html,解析URL参数并显示

在Users.html里解析URL里的参数,然后显示:

<div id="target">
</div>

<script>
window.onload = function() {
    // 获取URL参数
    const urlParams = new URLSearchParams(window.location.search);
    const content = urlParams.get('content');
    if (content) {
        // 解码后插入到target
        document.getElementById('target').textContent = decodeURIComponent(content);
    }
};
</script>

两种方法的区别

  • localStorage:适合存储稍长或需要保留一段时间的内容,数据存在本地,除非主动删除或清除浏览器缓存
  • URL参数:适合短内容,数据暴露在URL里,页面刷新后如果参数还在就会显示,不需要本地存储

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 02:57:54