javascript - 用DOM给网页插入表格时无显示。
本文介绍了javascript - 用DOM给网页插入表格时无显示。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
<!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);
解决方案
执行js的时候body还没加载,把script放在body内部或者用window.onload把js包起来可以解决问题
这篇关于javascript - 用DOM给网页插入表格时无显示。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文