如何在table.rows.length函数的html表中排除标题行?

时间:2012-12-24 12:32:06

标签: javascript html

Java脚本中的

table.rows.length 返回表中的行数,包括<thead>标记中的行。我需要的是,如果有一个只有<thead>元素的标题行(在<th>内),我想忽略该行,我只需要有数据的行数而不是标题元素。

注意:我无法使用table.rows.length - 1,因为我无法修改Javascript。我只能在HTML方面进行修改。这是代码示例代码段。在这里,我需要数为4而不是5。

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sample</title>
<script type="text/javascript">
function call(){    
    alert(document.getElementById('tab').rows.length);
}
</script>
</head>
<body onload="call()">
<table id="tab" border="1">
    <thead>
        <th>
          header 1
         </th>
         <th>
            header 2
         </th>           
    </thead>
    <tbody>
        <tr>
             <td> data1</td>
             <td> data1</td>
        </tr>
        <tr>
             <td> data2</td>
             <td> data2</td>
        </tr>
        <tr>
             <td> data3</td>
             <td> data3</td>
        </tr>
        <tr>
             <td> data</td>
             <td> data4</td>
        </tr>
    </tbody>    
  </table>  
 </body>
</html>

1 个答案:

答案 0 :(得分:1)

id重新分配给<tbody>元素:

<table border="1">
    <tbody id="tab">
    ...

由于此元素为<HTMLTableSectionElement>,因此它也具有rows(HTMLCollection)属性,因此您根本不需要在JS中进行任何更改。