本文實例講述了javascript實現Table間隔色以及選擇高亮(和動態切換數據)的方法。分享給大家供大家參考。具體實現方法如下:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 <!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.3lian.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程序設計有所幫助。