关联多个单选按钮以跳转不同URL的实现方案咨询
联动单选按钮跳转实现方案
针对你的需求,我们可以通过HTML结构搭建 + CSS控制显隐 + JavaScript逻辑联动的方式实现,代码简洁易懂,适合新手维护:
1. HTML结构
先搭建表单和单选按钮组,给每个选项设置明确的value方便后续判断,同时给第二、三组加初始隐藏的样式:
<form id="selectionForm"> <!-- 单选按钮组1 --> <div class="group"> <p>选择分组:</p> <label><input type="radio" name="group1" value="A" required> A</label> <label><input type="radio" name="group1" value="B" required> B</label> </div> <!-- 单选按钮组2 (初始隐藏) --> <div class="group group2" style="display: none;"> <p>选择子选项:</p> <label><input type="radio" name="group2" value="C" required> C</label> <label><input type="radio" name="group2" value="D" required> D</label> <label><input type="radio" name="group2" value="E" required> E</label> </div> <!-- 单选按钮组3 (初始隐藏) --> <div class="group group3" style="display: none;"> <p>选择子选项:</p> <label><input type="radio" name="group3" value="F" required> F</label> <label><input type="radio" name="group3" value="G" required> G</label> <label><input type="radio" name="group3" value="H" required> H</label> <label><input type="radio" name="group3" value="I" required> I</label> </div> <button type="submit">提交</button> </form>
2. JavaScript逻辑
分两部分实现:组1选择后的显隐切换、提交后的URL跳转,用对象映射选项和URL,后续修改更方便:
// 获取表单和各组元素 const form = document.getElementById('selectionForm'); const group1Radios = document.querySelectorAll('input[name="group1"]'); const group2 = document.querySelector('.group2'); const group3 = document.querySelector('.group3'); // 监听组1的选择变化,切换显示对应子组 group1Radios.forEach(radio => { radio.addEventListener('change', () => { if (radio.value === 'A') { group2.style.display = 'block'; group3.style.display = 'none'; // 隐藏组3时清空其选中状态,避免表单校验报错 document.querySelectorAll('input[name="group3"]').forEach(r => r.checked = false); } else if (radio.value === 'B') { group3.style.display = 'block'; group2.style.display = 'none'; document.querySelectorAll('input[name="group2"]').forEach(r => r.checked = false); } }); }); // 定义选项和对应URL的映射表 const urlMap = { 'C': 'URL1', 'D': 'URL2', 'E': 'URL3', 'F': 'URL4', 'G': 'URL5', 'H': 'URL6', 'I': 'URL7' }; // 监听表单提交事件,执行跳转 form.addEventListener('submit', (e) => { e.preventDefault(); // 阻止表单默认提交行为 // 获取最终选中的子选项值 let selectedValue = ''; const group2Checked = document.querySelector('input[name="group2"]:checked'); const group3Checked = document.querySelector('input[name="group3"]:checked'); if (group2Checked) { selectedValue = group2Checked.value; } else if (group3Checked) { selectedValue = group3Checked.value; } // 跳转对应URL if (urlMap[selectedValue]) { window.location.href = urlMap[selectedValue]; } });
3. 关键细节说明
- 用
name属性给单选按钮分组,同一组的name必须一致,确保同一时间只能选一个; - 给每个单选按钮设置
value,作为判断选中项的标识,比用文本内容更可靠; - 切换组时清空另一组的选中状态,避免浏览器表单校验报错;
- 用
urlMap对象存储选项和URL的对应关系,后续修改或新增选项时,直接修改这个对象即可,不用改动逻辑代码; - 表单加
required属性,确保用户必须完成所有选择才能提交。
内容的提问来源于stack exchange,提问作者btcjohnson
相关产品推荐
相关产品推荐

