html中用js实现的表格隔行换色

写的时候把自己的表

//写的时候把自己的表的table加上id="tbl"
<table id="tbl">

代码如下:


<html>
    <head>
        <meta charset="UTF-8">
        <title>表格隔行换色title>
        <script>
            window.onload = function(){
                //1.获取表格
                var tblEle = document.getElementById("tbl");
                //2.获取表格中tbody里面的行数(长度)
                var len = tblEle.tBodies[0].rows.length;
                //alert(len);
                //3.对tbody里面的行进行遍历
                for(var i=0;iif(i%2==0){
                        //4.对偶数行设置背景颜色
                        tblEle.tBodies[0].rows[i].style.backgroundColor="pink";
                    }else{
                        //5.对奇数行设置背景颜色
                        tblEle.tBodies[0].rows[i].style.backgroundColor="gold";
                    }
                }
            }
        script>

    head>
    <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>1td>
                    <td>张三td>
                    <td>22td>
                tr>
                <tr >
                    <td>2td>
                    <td>李四td>
                    <td>25td>
                tr>
                <tr >
                    <td>3td>
                    <td>王五td>
                    <td>27td>
                tr>
                <tr >
                    <td>4td>
                    <td>赵六td>
                    <td>29td>
                tr>
                <tr >
                    <td>5td>
                    <td>田七td>
                    <td>30td>
                tr>
                <tr >
                    <td>6td>
                    <td>汾九td>
                    <td>20td>
                tr>
            tbody>
        table>
    body>
html>

你可能感兴趣的:(js)