javaEE (四)javaweb_JavaScript (4) 表格變色:隔行變色
阿新 • • 發佈:2018-12-22
效果如圖所示,隔行變色
原始碼:
<!-- 新標籤: <thead> <tr> <th> </th> </tr> </thead> <tbody> <tr> <td> </td> </tr> </tbody> 1、選取事件:頁面載入事件onload 2、獲取元素:獲取表格(document.getElementById()),最終是為了獲取tbody裡面的行數(長度)--rows.length 3、js for迴圈 4、獲取奇數行和偶數行:遍歷角標對2取餘 5、設定背景顏色:style.backgroundColor 注:此時用了一個匿名函式,直接在<script>裡面用widows.onload = function() 載入--> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>表格隔行換色</title> </head> <script> window.onload = function()
{ //1、匿名函式獲得事件; var tblEle = document.getElementById("tbl"); //2、獲得元素; var len = tblEle.tBodies[0].rows.length; for(var i = 0 ; i < len ; i++){ //偶數紅,奇數灰; if(i % 2 == 0){ tblEle.tBodies[0].rows[i].style.backgroundColor = "red"; }else{ tblEle.tBodies[0].rows[i].style.backgroundColor = " gray"; } } } </script> <body> <table border="1" width="500" height="50" align="center" id="tbl"> <thead> <tr> <th>編號</th> <th>姓名</th> <th>年齡</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>張三</td> <td>22</td> </tr> <tr> <td>2</td> <td>李四</td> <td>25</td> </tr> <tr> <td>3</td> <td>王五</td> <td>27</td> </tr> <tr> <td>4</td> <td>趙六</td> <td>29</td> </tr> <tr> <td>5</td> <td>田七</td> <td>30</td> </tr> <tr> <td>6</td> <td>汾九</td> <td>20</td> </tr> </tbody> </table> </body> </html>