<html>
<head>
<title></title>
<style>
table{
width:800px;
border-collapse:collapse;
border:1px solid #9BC2E0;
}
table td,th{
width:120px;
height:30px;
font-size:13px;
border:1px solid #9BC2E0;
}
tr.even{
background:red;
}
tr.odd{
background:blue;
}
</style>
<script> window.onload = function createTable(){ var table = document.getElementById('tableId');
var tbody = document.createElement('tbody');
var k = 0;
//创建表格
for(var i = 0;i < 25;i ++){
var tr = document.createElement('tr');
for(var j = 0;j < 5;j ++){
var td = document.createElement('td');
var text = document.createTextNode(k ++);
td.appendChild(text);
tr.appendChild(td);
}
tbody.appendChild(tr);
}
table.appendChild(tbody); //隔N=3行换色,其中不包括首行
var trs = table.getElementsByTagName('tr');
for(var i = 1,len = trs.length;i < len;i ++){
/*if(i&1){
trs[i].className ='even';
}else{
trs[i].className = 'odd';
}*/
var j = parseInt((i - 1)/3);//隔N行
if(j&1){
trs[i].style.backgroundColor='#0f0';
}else{
trs[i].style.backgroundColor='#f00';
}
}
//事件委托
table.onclick = function(e){
//ie与firefox获取事件不同
var event = e || window.event;
var td = event.target || event.srcElement;
if(td.tagName === 'TD'){
alert(td.innerHTML);
}
};
}
</script>
</head>
<body>
<table id="tableId">
<thead>
<tr>
<th>head 1</th>
<th>head 2</th>
<th>head 3</th>
<th>head 4</th>
<th>head 5</th>
</tr>
</thead>
</table>
</body>
</html>
备注:关于创建表格的方式的另一种写法(提升性能):
var table = document.getElementById('tableId');
var tbody = document.createElement('tbody');
var k = 0;
//创建表格
//createDocumentFragment:创建文档碎片节点
var tbodydf = document.createDocumentFragment();
var trdf = document.createDocumentFragment();
for(var i = 0;i < 25;i ++){
var tr = document.createElement('tr');
for(var j = 0;j < 5;j ++){
var td = document.createElement('td');
var text = document.createTextNode(k ++);
td.appendChild(text);
trdf.appendChild(td);
}
tr.appendChild(trdf);
tbodydf.appendChild(tr);
}
tbody.appendChild(tbodydf);
table.appendChild(tbody);