【发布时间】:2014-05-25 01:30:47
【问题描述】:
我正在尝试创建一个动态 js 表,我想动态地为每个单元格提供 id。我想使用这些 id 在不同的 js 事件处理程序中使用。怎么做?我尝试了不同的方法,但都没有奏效!
<html>
<head>
<style>
#colors {
float: right;
width: 400px;
height: 400px;
}
</style>
</head>
<body>
<script>
var d;
var k = 0;
function makeit() {
var tbl = document.createElement("table");
var atts = document.createAttribute("style");
atts.value = "border:1px solid black;text-align:center;padding:2px;margin:3px 3px 3px 3px;";
tbl.setAttributeNode(atts);
for (i = 0; i < 5; i++) {
var rows = tbl.insertRow(i);
for (j = 0; j < 7; j++) {
d = rows.insertCell(j);
d.height = "50px";
d.width = "50px";
d.style.backgroundColor = "yellow";
d.addEventListener("click", function myfunc() { d.style.backgroundColor = "red"; });
}
}
document.body.appendChild(tbl);
}
window.onload = makeit;
</script>
</body>
</html>
【问题讨论】:
标签: javascript dynamic html-table