HTML页面间通过localStorage传递变量值失败问题求助
问题分析与修复方案
核心问题
你的代码存在两个关键错误,导致page2无法渲染存储的name值:
- page1中执行
window.location.href = 'page2.html'后立刻调用result()——页面跳转时,page1的JavaScript环境会被销毁,这个调用根本不会在page2中执行。 - page2的
result()函数没有被主动触发,且即便触发,DOMContentLoaded事件如果在页面加载完成后才绑定,也不会生效。
修复步骤
- 移除page1中无效的函数调用:跳转后page1代码停止运行,无需在
form_check()里调用result()。 - 让page2自动执行渲染逻辑:在page2加载时直接监听
DOMContentLoaded事件,读取localStorage并渲染内容。 - 规范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
相关产品推荐
相关产品推荐

