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

如何将复选框的值保存至sessionStorage并在另一页面加载时取回设置

解决方案

没问题,我来帮你实现这个功能!核心思路是利用sessionStorage存储选中的复选框值(注意它只能存字符串,所以要转成JSON格式),然后在第二页读取并恢复状态。

第一页:保存复选框状态到sessionStorage

修改你的saveSession函数,收集所有选中的复选框值,转成JSON字符串后存入sessionStorage:

<body>
 <label for="1">
 <input type="checkbox" name="num" id="1" checked="checked" value="1" >1
 </label>
 <label for="2">
 <input type="checkbox" name="num" id="2" value="2" >2
 </label>
 <label for="3">
 <input type="checkbox" name="num" id="3" value="3" >3
 </label>
 <label for="4">
 <input type="checkbox" name="num" id="4" value="4" >4
 </label>
 <button onclick="saveSession()">save</button>
 <script type="text/javascript">
 function saveSession() {
     // 1. 获取所有name为num的复选框
     const checkboxes = document.querySelectorAll('input[name="num"]');
     // 2. 过滤出选中的复选框,收集它们的value
     const checkedValues = Array.from(checkboxes)
         .filter(checkbox => checkbox.checked)
         .map(checkbox => checkbox.value);
     // 3. 转成JSON字符串存入sessionStorage(因为sessionStorage只能存字符串)
     sessionStorage.setItem('checkedNums', JSON.stringify(checkedValues));
     // 可选:提示保存成功
     alert('状态已保存!');
 }
 </script>
</body>

第二页:从sessionStorage恢复复选框状态

修改type函数,读取存储的JSON字符串,解析成数组后,给对应的复选框设置选中状态:

<body onload="type()">
 <label for="1">
 <input type="checkbox" name="num" id="1" value="1" >1
 </label>
 <label for="2">
 <input type="checkbox" name="num" id="2" value="2" >2
 </label>
 <label for="3">
 <input type="checkbox" name="num" id="3" value="3" >3
 </label>
 <label for="4">
 <input type="checkbox" name="num" id="4" value="4" >4
 </label>
 <script type="text/javascript">
 function type() {
     // 1. 从sessionStorage获取存储的字符串,默认空数组
     const savedValues = JSON.parse(sessionStorage.getItem('checkedNums')) || [];
     // 2. 获取所有复选框
     const checkboxes = document.querySelectorAll('input[name="num"]');
     // 3. 遍历复选框,判断是否在保存的数组中,设置选中状态
     checkboxes.forEach(checkbox => {
         checkbox.checked = savedValues.includes(checkbox.value);
     });
 }
 </script>
</body>

补充说明

  • sessionStorage是会话级存储,关闭浏览器标签页后数据会丢失,如果需要持久化可以换成localStorage
  • 确保两页的复选框name和value完全一致,否则无法正确匹配
  • 如果存储的内容为空(比如第一次打开第二页),JSON.parse会返回null,所以用|| []设置默认值避免报错

内容的提问来源于stack exchange,提问作者User not found

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 17:24:10