在编写一个html时,想要实现js中处理的数据输出并显示在浏览器的表格中,然后再写完代码后,报错Uncaught TypeError: Cannot set properties of null (setting 'innerHTML');
Cannot set properties of null (setting 'innerHTML'),这个报错的意思是无法读取null的属性“innerHTML”,即表示找不到你想要将所写的HTML代码插入的地方。
原因:浏览器加载HTML文档时,会将HTML文档解析为一个树形结构,称为DOM树,代码的执行顺序是自上而下依次执行,当执行到innerHTML这一行代码时,他并没有加载到下面的DOM结构,就会报错无法读取HTML。
解决办法:将DOM的读取部分的script放在body后面。或者在script标签中添加window.onload,等页面加载结束后再执行这一部分代码。
示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> *{ margin: 0; padding: 0; } div{ font-size: 14px; width: 200px; height: auto; margin: 50px auto; } table{ text-align: center; border-collapse:collapse; } table,tr,td,th{ border: 1px solid #ccc; } #t1 tr:nth-child(even){ color:red; } th{ font-weight: bold; } </style> <!-- 将这部分放在body之后解决问题 --> <!-- <script type="text/javascript"> var stuNum = 7; var stuSoc = new Array(); var sum = 0; var std = 0; var notPassNum = 0; for (var i = 0; i < stuNum; i++) { stuSoc[i] = prompt("请输入7个学生中第"+(i+1)+"个学生成绩分数:"); sum += parseInt(stuSoc[i]); if (stuSoc[i] < 60) { notPassNum++; } } std = parseFloat(sum/stuNum).toFixed(3); alert("总分:"+sum+","+"平均成绩:"+std+","+"不及格人数:"+notPassNum); for (var i = 0; i < stuNum; i++) { document.getElementById(i).innerHTML = stuSoc[i]; } document.getElementById("sum").innerHTML = sum; document.getElementById("std").innerHTML = std; document.getElementById("notPassNum").innerHTML = notPassNum; </script> --> </head> <body> <div id = "content"> <table id = "t1"> <tr> <th>序号</th> <th>分数</th> </tr> <tr> <td>1</td> <td id = "0"></td> </tr> <tr> <td>2</td> <td id = "1"></td> </tr> <tr> <td>3</td> <td id = "2"></td> </tr> <tr> <td>4</td> <td id = "3"></td> </tr> <tr> <td>5</td> <td id = "4"></td> </tr> <tr> <td>6</td> <td id = "5"></td> </tr> <tr> <td>7</td> <td id = "6"></td> </tr> </table> </div> <hr> <div id ="result" > <table id = "t2"> <tr> <th>统计项</th> <th>数值</th> </tr> <tr> <td>总分</td> <td id = "sum"></td> </tr> <tr> <td>平均成绩</td> <td id = "std"></td> </tr> <tr> <td>不及格人数</td> <td id = "notPassNum"></td> </tr> </table> </div> <script type="text/javascript"> var stuNum = 7; var stuSoc = new Array(); var sum = 0; var std = 0; var notPassNum = 0; for (var i = 0; i < stuNum; i++) { stuSoc[i] = prompt("请输入7个学生中第"+(i+1)+"个学生成绩分数:"); sum += parseInt(stuSoc[i]); if (stuSoc[i] < 60) { notPassNum++; } } std = parseFloat(sum/stuNum).toFixed(3); alert("总分:"+sum+","+"平均成绩:"+std+","+"不及格人数:"+notPassNum); for (var i = 0; i < stuNum; i++) { document.getElementById(i).innerHTML = stuSoc[i]; } document.getElementById("sum").innerHTML = sum; document.getElementById("std").innerHTML = std; document.getElementById("notPassNum").innerHTML = notPassNum; </script> </body> </html>
结果: