javascript - 用DOM给网页插入表格时无显示。
PHP中文网
PHP中文网 2017-04-11 13:11:53
0
1
316
<!DOCTYPE html>
<html>
 <head>
  <title> new document </title>  
</head>
<script type="text/javascript">
//创建table
var table = document.createElement("table");
table.border = "1";
table.width = "100%";

//创建tbody
var tbody = document.createElement("tbody");
table.appendChild(tbody);

//创建第一行
tbody.insertRow(0);
tbody.rows[0].insertCell(0);
tbody.rows[0].cells[0].appendChild(document.createTextNode("Cell 1,1"));
tbody.rows[0].insertCell(1);
tbody.rows[0].cells[1].appendChild(document.createTextNode("Cell 2,1"));

//创建第二行
tbody.insertRow(1);
tbody.rows[1].insertCell(0);
tbody.rows[1].cells[0].appendChild(document.createTextNode("Cell 1,2"));
tbody.rows[1].insertCell(1);
tbody.rows[1].cells[1].appendChild(document.createTextNode("Cell 2,2"));

//将表格添加到文档主体中
document.body.appendChild(table);

</script>
<body>



</body>
</html>

表格在页面中没有加载,控制台报错如下

Uncaught TypeError: Cannot read property 'appendChild' of null
    at 11.html:31

错误指向这一行 document.body.appendChild(table);

PHP中文网
PHP中文网

认证0级讲师

Antworte allen(1)
伊谢尔伦

执行js的时候body还没加载,把script放在body内部或者用window.onload把js包起来可以解决问题

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!