**实现效果:**动态生成N行M列表格,并且每个表格数字随机,背景颜色随机
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>面试题-动态生成表格</title>
<style>
body{
font:700 14px/1.5 Arial;margin:0;padding:0 10px;
}
table{
clear:both;border:1px solid #000;
}
td{
color:#ccc;cursor:pointer;text-align:center;
border:1px solid #000;padding:5px;
}
#setting{
float:left;clear:left;line-height:28px;
margin:10px 0;
}
#setting input{
width:50px;font-family:inherit;
border:2px solid #CCC;margin:0 5px;padding:4px;
}
#btn{
font-size:14px;line-height:18px;
color:#fff;text-decoration:none;
background:#353535;border-top:1px #999 solid;
border-radius:5px;padding:4px 6px;
}
#setting label,#setting input,#setting a,#msg span,#msg em{
float:left;
}
</style>
<script src="../js/common.js" type="text/javascript" charset="utf-8"></script>
<script>
function createTable(){
var rowCount = document.getElementById("row").value;
var colCount = document.getElementById("col").value;
//创建出来
var tab = document.createElement("table");
//把生成的table标签对象,放到页面上body元素的最后
document.body.appendChild(tab);
for(var i=0; i<rowCount; i++) {
var tr = document.createElement("tr");
tab.appendChild(tr);
for(var j=0; j<colCount; j++) {
var td = document.createElement("td");
td.innerHTML = Math.round(Math.random()*100);
td.style.background = '#' + Math.random().toString(16).slice(-6);
tr.appendChild(td);
}
}
}
</script>
</head>
<body>
<div id="setting">
<label>行数</label><input type="text" id="row">
<label>列数</label><input type="text" id="col">
<a href="javascript:;" onclick="createTable()" id="btn">生成表格</a>
</div>
</body>
</html>