本文實例講述了javascript實現Table間隔色以及選擇高亮(和動態切換數據)的方法。分享給大家供大家參考。具體實現方法如下:
<!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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Table間隔色以及選擇高亮(和動態切換數據)</title> <script type="text/javascript"> var Datas1 = { "李莫": "畢業於清華大學", "周平": "畢業於北京大學", "羅達": "畢業於哈爾濱大學", "鄭朵": "畢業於河南大學", "王天": "畢業於湖南大學" }; var Datas2 = { "": "http://www.jb51.net", "搜狐網": "http://www.souhu.com", "CSDN程序員開發網站": "http://www.csdn.net", "百度": "http://www.baidu.com", "網易": "http://www.163.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>
希望本文所述對大家的javascript程序設計有所幫助。