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

HTML页面间通过localStorage传递变量值失败问题求助

问题分析与修复方案

核心问题

你的代码存在两个关键错误,导致page2无法渲染存储的name值:

  1. page1中执行window.location.href = 'page2.html'后立刻调用result()——页面跳转时,page1的JavaScript环境会被销毁,这个调用根本不会在page2中执行。
  2. page2的result()函数没有被主动触发,且即便触发,DOMContentLoaded事件如果在页面加载完成后才绑定,也不会生效。

修复步骤

  1. 移除page1中无效的函数调用:跳转后page1代码停止运行,无需在form_check()里调用result()。
  2. 让page2自动执行渲染逻辑:在page2加载时直接监听DOMContentLoaded事件,读取localStorage并渲染内容。
  3. 规范localStorage操作:用localStorage.getItem()替代直接属性访问,避免潜在的属性冲突。

修改后的代码

page1 HTML(无结构改动)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>page1</title>
</head>
<body>
    <form>
        <label>Name:</label>
        <input type="text" id="name">
    </form>
    <button type="button" onclick="form_check()">Submit</button>
    <script src="/script.js"></script>
</body>
</html>

page2 HTML(无结构改动)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" src="/style.css">
    <title>page2</title>
</head>
<body>
    <p>The name was introduced: <i id="name_result"></i></p>
    <script src="/script.js"></script>
</body>
</html>

修改后的JavaScript

// page2加载时自动执行渲染逻辑
document.addEventListener('DOMContentLoaded', function() {
    const nameValue = localStorage.getItem('name_result');
    if (nameValue) {
        document.getElementById('name_result').textContent = nameValue;
    }
});

function form_check() {
    const name = document.getElementById('name').value.trim();
    localStorage.setItem('name_result', name);
    window.location.href = 'page2.html';
}

额外优化提示

  • 用textContent替代innerHTML更安全,可避免输入内容包含HTML标签时的XSS风险。
  • 可添加输入校验逻辑,比如判断name为空时不执行跳转和存储操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 17:22:54