<html>
<head>
<title>实例代码 - 使用JavaScript和DOM创建HTML表格</title>
<script>
function start() {
//获取body标签
var mybody = document.getElementsByTagName("body")[0];
// 创建一个<table>元素和一个<tbody>元素
table1 = document.createElement("table");
mytablebody = document.createElement("tbody");
//创建所有的单元格
myArray = new Array('this','is','a','test');
for(var j = 0; j <4; j++) {
// 创建一个<tr>元素
mycurrent_row = document.createElement("tr");
for(var i = 0; i <4; i++) {
// 创建一个<td>元素--列
mycurrent_cell = document.createElement("td");
//创建一个文本节点
if(j==0){
currenttext = document.createTextNode(myArray[i]);
}else if(i==0){
currenttext = document.createTextNode(myArray[j]);
}else {currenttext = document.createTextNode();
}
mycurrent_cell.appendChild(currenttext);
// 将列<td>添加到行<tr>
mycurrent_row.appendChild(mycurrent_cell);
}
// 将行<tr>添加到<tbody>
mytablebody.appendChild(mycurrent_row);
}
// 将<tbody>添加到<table>
table1.appendChild(mytablebody);
//将<table>添加到<body>
mybody.appendChild(table1);
table1.setAttribute("border", "2");
table1.setAttribute("cellspacing", "3");
table1.setAttribute("cellpadding", "2");
}
</script>
</head>
<body onload="start()">
</body>
</html>