单选按钮切换表格显示状态失效问题求助
单选按钮切换表格显示样式无效的排查原因
我想通过切换单选按钮来改变表格的显示样式,但编写的JavaScript和HTML代码完全没有效果,参考多个网站的实现方式修改后依然无法解决问题,请问可能的原因是什么?
JavaScript 代码
function changeStylePruefung(radiobutton) { if (radiobutton.value === "stoerungsbehebung") { document.getElementById("table-stoerung").style.display = "block"; document.getElementById("table-haupt").style.display = "none"; } else { document.getElementById("table-stoerung").style.display = "none"; document.getElementById("table-haupt").style.display = "block"; } }
HTML 代码
<fieldset id="uberpruefung"> <legend style="font-weight: bold">Prüfung im Rahmen einer</legend> <div> <label for="stoerungbeh">Störungsbehebung</label> <input type="radio" id="stoerungbeh" name="pruefung" value="stoerungsbehebung" onchange="changeStylePruefung(this)" checked><br> </div> <div> <label for="hauptpruefung">Hauptprüfung</label> <input type="radio" id="hauptpruefung" name="pruefung" value="hauptpruefung" onchange="changeStylePruefung(this)"> </div> </fieldset> <br><br> <fieldset> <legend style="font-weight: bold">In Ordnung</legend> <div class='table-haupt' style="display: none"> <table class='rg-table' summary='Hed'> ..... </table> </div> <div class='table-stoerung' style="display: block"> <table class='rg-table-stoerung' summary='Hed'> ..... </table> </div> </fieldset>
问题原因与修复方案
核心问题:元素选择器不匹配
你的JavaScript代码里使用document.getElementById()查找元素,但HTML中包裹表格的div仅设置了class属性(table-haupt、table-stoerung),并没有对应的id属性,导致JS无法定位到目标元素,自然无法修改显示样式。打开浏览器控制台(F12)会看到类似Cannot set properties of null的报错信息。两种修复方式
修改HTML,添加id属性
给包裹表格的div加上对应id:<div id='table-haupt' style="display: none"> <table class='rg-table' summary='Hed'> ..... </table> </div> <div id='table-stoerung' style="display: block"> <table class='rg-table-stoerung' summary='Hed'> ..... </table> </div>修改JavaScript,使用class选择器
把getElementById替换为querySelector来匹配class:function changeStylePruefung(radiobutton) { const stoerungDiv = document.querySelector(".table-stoerung"); const hauptDiv = document.querySelector(".table-haupt"); if (radiobutton.value === "stoerungsbehebung") { stoerungDiv.style.display = "block"; hauptDiv.style.display = "none"; } else { stoerungDiv.style.display = "none"; hauptDiv.style.display = "block"; } }
内容的提问来源于stack exchange,提问作者niki.orihatza
相关产品推荐
相关产品推荐

