根據自己所輸入的寬、高、行、列來指定自己所要創建的表格。
源代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="WEB-INF/js/jquery-3.1.1.min.js"></script>
<title>Title</title>
</head>
<body>
寬:<input type="text" id="w"><br/>
高:<input type="text" id="h"><br/>
行:<input type="text" id="c"><br/>
列:<input type="text" id="r"><br/>
<input type="button" value="創建表格" id="btn">
<script type="text/javascript">
document.getElementById("btn").onclick = function() {
// 獲取屬性
var w = document.getElementById("w").value + "px";
var h = document.getElementById("h").value + "px";
var c = parseInt(document.getElementById("c").value);
var r = parseInt(document.getElementById("r").value);
// 使用dom創建並設置顏色
var table = document.createElement("table");
table.setAttribute("width",w);
table.setAttribute("cellspacing",0);
table.setAttribute("height",h);
table.setAttribute("border","1px");
// 外層是行內層是列
for (var i = 0; i < c; i++){
var tr = document.createElement("tr");
// 隔行變色
if(i % 2 == 0){
tr.style.background="red";
}else{
tr.style.background="blue";
}
for (var j = 0; j < r; j++){
var td = document.createElement("td");
tr.appendChild(td);
};
table.appendChild(tr);
}
// 把table添加到頁面中
document.body.appendChild(table);
}
</script>
</body>
</html>