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

如何在HTML页面中保存一页结果并在另一页调用展示?

跨HTML页面保存并展示数据的实现方案

核心思路

使用浏览器的localStorage实现同源页面间的数据共享,它会将数据持久化存储在本地(除非手动清除),同源的任意页面都可以读取和修改。


一、第一页:完善后的数据保存代码

你的原代码存在执行时机问题——如果脚本在DOM元素渲染前运行,getElementById会返回null,导致保存失败。修正后确保DOM加载完成再执行:

<script>
// 等待页面DOM完全加载后执行
document.addEventListener('DOMContentLoaded', function() {
    const totalPriceElement = document.getElementById("total-price");
    // 先校验元素是否存在,避免报错
    if (totalPriceElement) {
        localStorage.setItem("totalPrice", totalPriceElement.innerText);
    }
});
</script>

二、第二页:读取并展示数据的代码

原代码仅获取了数据,但没有将其展示到页面上。以下是完整的读取并渲染代码(假设页面中有一个id为display-total的元素用于展示结果):

<script>
document.addEventListener('DOMContentLoaded', function() {
    const totalPrice = localStorage.getItem("totalPrice");
    const displayElement = document.getElementById("display-total");
    // 校验数据和展示元素是否存在
    if (displayElement && totalPrice) {
        displayElement.innerText = `总价:${totalPrice}`;
    }
});
</script>

额外注意事项

  • 同源限制:只有协议、域名、端口完全一致的页面才能共享localStorage数据,跨域页面无法访问。
  • 数据类型处理:localStorage仅支持存储字符串,若要保存数字、对象等类型,需用JSON.stringify()转换,读取时用JSON.parse()解析:
    保存数字示例:
    localStorage.setItem("totalPrice", JSON.stringify(parseFloat(totalPriceElement.innerText)));
    
    读取数字示例:
    const totalPrice = JSON.parse(localStorage.getItem("totalPrice"));
    
  • 清理数据:不再需要数据时,可通过localStorage.removeItem("totalPrice")手动删除,避免占用本地存储空间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 07:52:52