JavaScript 操作table,可以新增行和列并且隔一行换背景色代码分享
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>JavaScript</title>
</head>
<body>
<script language="javascript">
var n = 0;
function showTable(len) {
wi('<table border="1" width="300" style="border-collapse:collapse"><tbody id="table">');
for (i=0;i<len;i++) {
if (parseInt(i%2)==1) {
bg = '#F4FAC7';
} else {
bg = 'white';
}
wi('<tr bgcolor='+bg+'><td>第'+(i+1)+'行</td></tr>');
}
wi('</tbody></table><br />');
wi('<input type="button" value="Add" id="add" />');
}
function wi(str) {
return document.write(str);
}
showTable(10);
var add = document.getElementById("add");
add.onclick = function() {
n = n+1;
if (n%2==0) {
bg = '#F4FAC7';
} else {
bg = 'white';
}
var table = document.getElementById("table");
var tr = document.createElement("tr");
tr.bgColor = bg;
var td = document.createElement("td");
td.innerHTML = '第'+(10+n)+'行';
tr.appendChild(td);
table.appendChild(tr);
}
</script>
</body>
</html>