点击复选框用JavaScript给HTML表格主体追加新行的问题排查
问题诊断与修复
你的代码在勾选复选框时无反应,核心问题是JavaScript API拼写错误:document.getElementByID里的ID应该是小写的Id,正确写法是document.getElementById。这个拼写错误会导致代码执行到这一行时抛出异常,后续的alert和插入表格行的逻辑都无法运行。
修复后的完整代码
<!doctype html> <html> <head> <h1>Checkbox Test</h1> </head> <body> <table class="tb" id="checky"> <thead> <tr> <th>Checkbox 1</th> <th>Checkbox 2</th> </tr> </thead> <tbody> <tr> <td><input type="checkbox" name="Team1_checkbox" id="1" onchange="doalert(this)" /> </td> <td><input type="checkbox" name="Team2_checkbox" id="2" onchange="doalert(this)" /> </td> </tr> </tbody> </table> <script> function doalert(checkboxElem) { if (checkboxElem.checked) { var table=document.getElementById("checky"); // 修正拼写错误 var row=table.insertRow(0); alert("checked"); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); cell1.innerHTML = "NEW CELL1"; cell2.innerHTML = "NEW CELL2"; } else { alert("notchecked"); } } </script> </body> </html>
额外提示
- 可以打开浏览器的开发者工具(F12)查看控制台(Console),这类拼写错误会在这里明确抛出
TypeError: document.getElementByID is not a function的异常,方便快速定位问题。 - 插入行时
insertRow(0)会把新行添加到表格的最顶部,如果你想添加到tbody内部,可以改为table.tBodies[0].insertRow(0),避免新行出现在thead上方。
内容的提问来源于stack exchange,提问作者MicroscopicPie
相关产品推荐
相关产品推荐

