所以我试图找出一种使用document.createElement()和node.appendChild()将行和表格单元连接在一起的方法,但我对这些命令有点新意。
<!DOCTYPE html>
<html onmousedown='event.preventDefault();'>
<head>
<title> Boxes </title>
<meta charset='utf-8'>
<style>
table {
border-spacing: 6px;
border: 1px rgb(#CCC);
margin-top: .5in;
margin-left: 1in;
}
td {
width: 40px; height: 40px;
border: 1px solid black;
cursor: pointer;
}
</style>
<script>
function colorize(el) {
var
r = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
g = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
b = ('0'+(Math.random()*255|0).toString(16)).slice(-2);
el.style.backgroundColor = '#' +r+g+b;
}
</script>
填写用id&#39; tb&#39;标识的表体tbody元素,使用文档&#34;创建元素&#34;使其成为16x16表。和&#34;节点追加孩子&#34;创建行和表格单元格并将它们连接在一起的方法。
我知道它需要类似&#34;文件正文追加儿童(k)&#34;与var一起反映正确的创建,例如&#34; var k = document create element&#34;
</head>
<body onload='maketable();'>
<table>
<tbody id='tb'>
<script type="text/javascript">
var row = 16;
var cols = 16;
for(var r=0;r<row;r++){
document.write("</tr>");
for(var c=0;c<cols;c++){
document.write("<td onMouseEnter='colorize(this);'></td>");
}
document.write("</tr>");
}
</script>
</tbody>
</table>
</body>
</html>
答案 0 :(得分:0)
以下是appendChild的示例。查看代码时的注释
function colorize(el) {
r = ('0' + (Math.random() * 255 | 0).toString(16)).slice(-2),
g = ('0' + (Math.random() * 255 | 0).toString(16)).slice(-2),
b = ('0' + (Math.random() * 255 | 0).toString(16)).slice(-2);
el.target.style.backgroundColor = '#' + r + g + b;
}
var row = 16;
var cols = 16;
// create a table element first
var table = document.createElement("table");
table.id = "tb"
for (var r = 0; r < row; r++) {
var row = document.createElement("tr");
table.appendChild(row);
for (var c = 0; c < cols; c++) {
var cell = document.createElement("td");
//add A mouse enter event to each cell
cell.addEventListener('mouseenter', colorize)
cell.innerHTML = "cell";
//append the cell object created to the row in focus
row.appendChild(cell)
}
}
//finally append the table to the body
document.body.appendChild(table);
table {
border-spacing: 6px;
border: 1px rgb(#CCC);
margin-top: .5in;
margin-left: 1in;
}
td {
width: 40px;
height: 40px;
border: 1px solid black;
cursor: pointer;
}