如何在JavaScript中获取上一页选中的单选按钮值以控制下一页表单?
如何在两个页面间传递单选按钮值并控制表单区域
当然可以实现,下面是几种常用的JavaScript方案,直接就能用:
方案1:通过URL参数传递
这种方式最简单直接,把选中值拼在跳转的URL里,第二个页面解析参数即可。
第一个页面(page1.html)代码:
<!-- 第一个表单示例 --> <form> <input type="radio" name="user-option" value="basic" id="basic-option"> <label for="basic-option">基础选项</label> <input type="radio" name="user-option" value="advanced" id="advanced-option"> <label for="advanced-option">进阶选项</label> <button type="button" id="continue-btn">继续</button> </form> <script> const continueBtn = document.getElementById('continue-btn'); const radioOptions = document.querySelectorAll('input[name="user-option"]'); continueBtn.addEventListener('click', () => { // 筛选出选中的单选按钮 const selected = Array.from(radioOptions).find(radio => radio.checked); if (!selected) { alert('请先选择一个选项'); return; } // 跳转到第二个页面并携带参数,encodeURIComponent处理特殊字符 window.location.href = `page2.html?option=${encodeURIComponent(selected.value)}`; }); </script>
第二个页面(page2.html)代码:
<!-- 第二个表单示例 --> <form> <div id="basic-area"> <label>基础区域输入:</label> <input type="text" name="basic-input"> </div> <div id="advanced-area"> <label>进阶区域输入:</label> <input type="text" name="advanced-input"> </div> </form> <script> // 解析URL中的参数 const params = new URLSearchParams(window.location.search); const selectedOption = params.get('option'); if (selectedOption) { // 根据选中值禁用对应区域 if (selectedOption === 'basic') { // 禁用进阶区域的所有表单元素 document.querySelectorAll('#advanced-area input').forEach(el => el.disabled = true); } else if (selectedOption === 'advanced') { document.querySelectorAll('#basic-area input').forEach(el => el.disabled = true); } } </script>
方案2:使用localStorage存储值
如果不想把参数暴露在地址栏,可以用localStorage临时存储选中值,第二个页面读取后再清理。
第一个页面修改后的JS:
continueBtn.addEventListener('click', () => { const selected = Array.from(radioOptions).find(radio => radio.checked); if (!selected) { alert('请先选择一个选项'); return; } // 把值存在localStorage localStorage.setItem('selectedUserOption', selected.value); window.location.href = 'page2.html'; });
第二个页面修改后的JS:
const selectedOption = localStorage.getItem('selectedUserOption'); if (selectedOption) { // 禁用对应区域逻辑和之前一致 if (selectedOption === 'basic') { document.querySelectorAll('#advanced-area input').forEach(el => el.disabled = true); } else if (selectedOption === 'advanced') { document.querySelectorAll('#basic-area input').forEach(el => el.disabled = true); } // 用完后删除存储的值,避免下次进入页面残留旧数据 localStorage.removeItem('selectedUserOption'); }
方案3:使用sessionStorage临时存储
和localStorage用法几乎一样,但sessionStorage的数据只在当前浏览器标签页有效,关闭标签页就会自动清除,适合不需要持久保存的场景:
第一个页面存储:
sessionStorage.setItem('selectedUserOption', selected.value);
第二个页面读取:
const selectedOption = sessionStorage.getItem('selectedUserOption'); // 处理逻辑... sessionStorage.removeItem('selectedUserOption');
各方案对比
- URL参数:简单易实现,缺点是参数暴露在地址栏,不适合敏感数据,且有长度限制。
- localStorage:数据持久化,即使关闭浏览器再打开也能读取(除非手动清除),适合需要跨会话保留数据的场景,但记得用完清理。
- sessionStorage:仅当前会话有效,安全性更高,适合临时传递数据的场景。
内容的提问来源于stack exchange,提问作者Amarthya reddy
相关产品推荐
相关产品推荐

