
当使用 `window.location.href` 跳转页面时,原页面的 javascript 执行立即终止,因此后续 localstorage 操作(如读取)必须在目标页中完成,而非跳转前或跳转后同一上下文内执行。
在 Web 开发中,localStorage 是一种常用的客户端持久化存储机制,但其行为常被误解——尤其在涉及页面跳转时。你遇到的问题非常典型:在 A 页面(如 x.html)中调用 localStorage.setItem() 后立即执行 window.location.href = "/testpage.html",却期望在同一脚本块中(即跳转前)或在新页面加载后的同一段 JS 里读取该值,这是不可行的。
根本原因在于:window.location.href 触发的是同步导航,浏览器会立即卸载当前页面、销毁其执行上下文(包括所有未执行完的 JS 代码),并开始加载新页面。因此,任何写在跳转语句之后的逻辑(哪怕只是 console.log)都不会执行;而你在 x.html 中写的 $(document).ready(...) 读取逻辑,也根本不会在 testpage.html 中运行——它只属于 x.html 的 DOM 就绪钩子。
✅ 正确做法是:写入与读取严格分离到两个独立页面的生命周期中:
- 写入阶段(源页面 x.html):仅负责收集选中状态并存入 localStorage,然后跳转;
- 读取阶段(目标页面 testpage.html):在自身 DOM 加载完成后,从 localStorage 中读取并还原状态。
以下是优化后的完整示例:
x.html(提交页)
<input type="checkbox" name="names" value="user1" onchange="submit(this)" />
<input type="checkbox" name="names" value="user2" onchange="submit(this)" />
<input type="checkbox" name="names" value="user3" onchange="submit(this)" />
<script>
function submit() {
const checkboxes = document.querySelectorAll('input[name="names"]');
checkboxes.forEach(cb => {
// 使用 checkbox 的 value 作为 key,更合理(避免全部用 true 作 key)
if (cb.checked) {
localStorage.setItem(`checkbox_${cb.value}`, 'checked');
} else {
localStorage.removeItem(`checkbox_${cb.value}`); // 清理未选中项
}
});
window.location.href = "/testpage.html";
}
</script>testpage.html(目标页)
<input type="checkbox" name="names" value="user1" />
<input type="checkbox" name="names" value="user2" />
<input type="checkbox" name="names" value="user3" />
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
const checkboxes = document.querySelectorAll('input[name="names"]');
checkboxes.forEach(cb => {
const key = `checkbox_${cb.value}`;
if (localStorage.getItem(key) === 'checked') {
cb.checked = true; // 推荐直接赋值布尔属性,而非 setAttribute
}
});
});
</script>⚠️ 注意事项:
- ❌ 不要用 names[i].checked(布尔值)作为 localStorage 的 key —— 所有选中项都会写入 "true" 这一相同 key,造成覆盖;
- ✅ 应使用有意义的唯一标识(如 value、id 或 data-id)作为 key;
- ✅ 使用 element.checked = true/false 直接操作 DOM 属性,比 setAttribute('checked', ...) 更符合现代标准;
- ✅ 跳转前可调用 localStorage.removeItem() 清理旧状态,避免脏数据;
- ? 若涉及敏感信息,请勿使用 localStorage(易被 XSS 窃取),改用服务端会话或加密临时 token。
总结:localStorage 是跨页面共享数据的有效工具,但必须尊重浏览器的页面生命周期。只要确保「写」在跳转前、「读」在目标页就绪后,即可稳定实现状态持久化与还原。










