表格的控制-动态地为表格中的单元格文字添加样式

————————————————————

<script type="text/javascript">        
            //为表格改变样式的函数
            function chCell(){
                //获取DOM
                var tbl = document.getElementById('tbl');
                var rows = tbl.rows;            //得到当前的表格的row数组
                var len = tbl.rows.length;        //当前的行数
                for(var i=1;i<len;i++){            //遍历所有行
                    var cells = rows[i].cells;    //得到这一行的所有单元格
                    //遍历单元格
                    for(var j=0;j<cells.length;j++){
                        cells[j].onclick = function(){//定义单元格的click事件
                            //如果字体的颜色是默认的或者黑色
                            if(this.style.color == '' || this.style.color == 'black')
                                //把单元格的字体变成红色
                                this.style.color = 'red';
                            else
                                //把单元格的字体变成黑色
                                this.style.color = 'black';
                        };
                    }
                }
            }
        </script>

————————————————————————————

<body style="text-align:center" onload="chCell();">
        <table id="tbl" align="center" border="1">
            <tr>
                <th>名字</th>
                <th>年龄</th>
            </tr>
            <tr>
                <td>A</td>
                <td>12</td>
            </tr>
            <tr>
                <td>B</td>
                <td>11</td>
            </tr>
            <tr>
                <td>C</td>
                <td>15</td>
            </tr>
        </table>
    </body>

——————————————————————————————

 

posted @ 2016-09-22 21:10  承载梦想-韩旭明  阅读(208)  评论(0编辑  收藏  举报