<html>
<head>
<title>运用js创建表格</title>
</head>
<body>
<table>
</table>
<script type="text/javascript">
/*function createTable(){
var body = document.body;
var table = document.createElement("table");
var tr = document.createElement("tr");
var td = document.createElement("td");
var txt = document.createTextNode("hello,world");
td.appendChild(txt);
tr.appendChild(td);
table.appendChild(tr);
table.style.border = "1px solid black";
body.appendChild(table);
}*/
function createDuoTable(){
var body = document.body;
var table = document.createElement("table");
for(var i=0;i<4;i++){
var tr = document.createElement("tr");
var td = document.createElement("td");
var txt = document.createTextNode("hello,world");
td.appendChild(txt);
tr.appendChild(td);
table.appendChild(tr);
td.style.border = "1px solid black";
if(i%2){
tr.style.backgroundColor = "#DDD";
} else {
tr.style.backgroundColor = "green";
}
}
table.style.border = "1px solid black";
body.appendChild(table);
}
createDuoTable();
</script>
</body>
</html>
效果如下: