如何根据单选框(Radio Box)的选中状态实现页面跳转?
单选框选中状态跳转页面的实现方法
你的代码存在两个核心问题,导致无法正常运行:
- 同一组单选框的
name属性必须一致,你设置的name="1"和name="2"会让两个单选框成为独立选项,无法实现互斥选择。 <input type="radio">原生不支持href属性,添加该属性不会触发页面跳转。
以下是两种可行的实现方案:
方案一:点击单选框直接跳转
这种方式会在用户选中单选框的瞬间触发页面跳转:
<label>选择目标页面:</label> <input type="radio" name="pageJump" value="1.html" id="page1"> <label for="page1">页面1</label> <input type="radio" name="pageJump" value="2.html" id="page2"> <label for="page2">页面2</label> <script> // 获取所有同组的单选框 const radioButtons = document.querySelectorAll('input[name="pageJump"]'); // 为每个单选框绑定点击事件 radioButtons.forEach(radio => { radio.addEventListener('click', function() { if (this.checked) { window.location.href = this.value; } }); }); </script>
说明:将单选框的value设置为目标页面地址,统一name属性保证互斥,点击选中时直接通过window.location.href跳转。
方案二:提交表单时根据选中状态跳转(含未选中默认逻辑)
如果需要用户先选择,再通过提交按钮确认跳转,同时处理未选中的默认情况:
<form id="jumpForm"> <label>选择目标页面:</label> <input type="radio" name="pageJump" value="1.html" id="page1"> <label for="page1">页面1</label> <input type="radio" name="pageJump" value="2.html" id="page2"> <label for="page2">页面2</label> <button type="submit">确认跳转</button> </form> <script> const jumpForm = document.getElementById('jumpForm'); jumpForm.addEventListener('submit', function(e) { // 阻止表单默认提交行为 e.preventDefault(); // 获取选中的单选框 const selectedRadio = document.querySelector('input[name="pageJump"]:checked'); if (selectedRadio) { // 有选中项,跳转到对应页面 window.location.href = selectedRadio.value; } else { // 未选中任何选项,跳转到默认页面 window.location.href = 'default.html'; } }); </script>
说明:表单提交时先检查是否有选中的单选框,存在则跳转到对应地址,否则跳转到预设的默认页面。
内容的提问来源于stack exchange,提问作者MALIKSI CHARLIE P
相关产品推荐
相关产品推荐

