例子,js实现表格隔行变色,选中后高亮显示。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Table间隔色以及选择高亮--www.jb200.com</title>
<script type="text/javascript">
var Datas1 = {
"李莫": "毕业于清华大学",
"周平": "毕业于北京大学",
"罗达": "毕业于哈尔滨大学",
"郑朵": "毕业于河南大学",
"王天": "毕业于湖南大学"
};
var Datas2 = {
"脚本 学堂": "http://www.jb200.com",
"搜狐网": "http://www.souhu.com",
"CSDN程序员开发网站": "http://www.csdn.net",
"百度": "http://www.baidu.com",
"深圳公积金网站": "http://www.szzfgjj.com"
};
function ToggleData() {
var btn = document.getElementById("btnToggle");
if (btn.value == "数据1") {
loadData(Datas1, "数据2");
}
else {
loadData(Datas2, "数据1");
}
}
function loadData(Datas,btnValue) {
var tblMain = document.getElementById("tblMain");
//清空table数据
var trs = tblMain.getElementsByTagName("tr");
var trsLen = trs.length; //必须先把trs的长度存放到一个变量中
for (var i = 0; i < trsLen; i++) {
tblMain.deleteRow(0);
}
var nIndex = 0;
for (var key in Datas) {
var tr = tblMain.insertRow(-1);
tr.onmouseover = trMouseOver;
tr.onmouseout = trMouseOut;
var td1 = tr.insertCell(-1);
td1.innerHTML = key;
var td2 = tr.insertCell(-1);
td2.innerHTML = Datas[key];
if (nIndex % 2 == 0) { //设置间隔色
tr.style.background = "yellow";
}
else {
tr.style.background = "white";
}
nIndex++;
}
var btn = document.getElementById("btnToggle");
btn.value = btnValue;
}
function trMouseOver() {
var tblMain = document.getElementById("tblMain");
//清空数据
var trs = tblMain.getElementsByTagName("tr");
for (var i = 0; i < trs.length; i++) {
if (this == trs[i]) {
trs[i].style.background = "green";
}
}
}
function trMouseOut() {
var tblMain = document.getElementById("tblMain");
var trs = tblMain.getElementsByTagName("tr");
for (var i = 0; i < trs.length; i++) {
if (i % 2 ==0) {
trs[i].style.background = "yellow";
}
else {
trs[i].style.background = "white";
}
}
}
function iniEvent() {
loadData(Datas1, "数据2");
}
</script>
</head>
<body onload="iniEvent()">
<table id="tblMain">
<tbody></tbody>
</table>
<input type ="button" id="btnToggle" value="数据2" onclick="ToggleData()" />
</body>
</html>