javascript实现Table间隔色以及选择高亮(和动态切换

本文实例讲述了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 = { "脚本之家": "https://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> <table> <tbody></tbody> </table> <input type ="button" value="数据2" /> </body> </html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgjzwy.html