获取table表格有多少列代码实例
分类:实例代码
本章节通过代码实例介绍一下如何获取table表格有多少列。
原理非常的简单,就是获取一个tr中有多少td单元格,即是表格有多少列。
代码实例如下:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.pipipi.net/" /> <title>前端教程网</title> <style type="text/css"> body, table{font-size:12px;} table{ table-layout:fixed; empty-cells:show; border-collapse: collapse; margin:0 auto; } td{height:30px;} h1, h2, h3{ font-size:12px; margin:0; padding:0; } .table{ border:1px solid #cad9ea; color:#666; } .table th{ background-repeat:repeat-x; height:30px; } .table td, .table th{ border:1px solid #cad9ea; padding:0 1em 0; } .table tr.alter{ background-color:#f5fafe; } #show { width:200px; height:50px; margin:0px auto; text-align:center; color:red; font-size:16px; } </style> <script> window.onload = function () { var otable = document.getElementById("antzone"); var odiv = document.getElementById("show"); var num = otable.getElementsByTagName("tr")[1].getElementsByTagName("td").length; odiv.innerHTML = num; } </script> </head> <body> <div id="show"></div> <table id="antzone" width="90%" class="table"> <tr> <th>学号</th> <th>姓名</th> <th>平时</th> <th>期中</th> <th>实验(践)</th> <th>其它</th> <th>期末</th> <th>总评</th> </tr> <tr> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> </tr> <tr class="alter"> <td>2</td> <td>2</td> <td>2</td> <td>2</td> <td>2</td> <td>2</td> <td>2</td> <td>2</td> </tr> </table> </body> </html>
上面的代码实现了我们的要求,代码比较简单,更多内容可以参阅相关阅读。
相关阅读:
(1).getElementsByTagName()可以参阅document.getElementsByTagName()一章节。
(2).innerHTML可以参阅js innerHTML一章节。