如何获取label标签内radio button的取值?新手技术求助
问题分析与解决方案:无法通过label内的radio按钮控制表格行显示/隐藏
嘿,我看了你的代码,发现问题其实出在重复的ID属性上——这是新手很容易踩的坑!
你把id1和id2同时用在了<tr>和它下面的<td>标签上,但HTML里要求id必须是全局唯一的。当你调用document.getElementById("id1")时,它只会找到页面上第一个带有这个id的元素(也就是第一个<td>),根本没作用到你想要控制显示/隐藏的表格行(<tr>)上,这就导致你的逻辑完全没生效!
另外还有个小细节:HTML里的<input>标签是自闭合的,不需要写</input>哦。
修正后的完整代码
JavaScript部分
function myButtonTrigger(c) { // 先获取到需要控制的表格行 const dentalRow = document.getElementById("id1"); const rehabRow = document.getElementById("id2"); if (c.value === "1") { dentalRow.style.display = "table-row"; rehabRow.style.display = "none"; } else if (c.value === "2") { dentalRow.style.display = "none"; rehabRow.style.display = "table-row"; } }
CSS部分(保持不变)
table { border-collapse: collapse; } table, th, td { border: 1px solid black; background-color: #39739D; color: white; }
HTML部分(修正ID问题,去掉多余的闭合标签)
<div class="btn-group" data-toggle="buttons"> <label class="btn btn-default"> <input value="1" type="radio" name="choices" onClick="myButtonTrigger(this)"> Dental </label> <label class="btn btn-default"> <input value="2" type="radio" name="choices" onClick="myButtonTrigger(this)"> Rehab </label> </div> <p>这是需要隐藏的数据:</p> <table> <tr id="id1"> <td>Dental Data</td> <td>Specialization Data1</td> <td>Schedule Data</td> <td>Room Data</td> </tr> <tr id="id2"> <td>Rehab Data</td> <td>Specialization Data2</td> <td>Schedule Data</td> <td>Room Data</td> </tr> </table>
额外优化建议(可选)
如果你想让代码更符合现代前端写法,可以去掉内联的onClick事件,改用事件监听的方式绑定:
// 页面加载完成后绑定事件 document.addEventListener('DOMContentLoaded', function() { // 获取所有name为choices的radio按钮 const radioButtons = document.querySelectorAll('input[name="choices"]'); radioButtons.forEach(button => { button.addEventListener('change', function() { myButtonTrigger(this); }); }); });
然后把HTML里的onClick="myButtonTrigger(this)"删掉就好啦。
内容的提问来源于stack exchange,提问作者pjustindaryll
相关产品推荐
相关产品推荐

