Javascript 不使用 jquery 计算表中的行数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8369467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Counting the number of rows in a table NOT using jquery
提问by phpmeh
<head>
<script language="javascript">
// must have the onload handler
onload = function countRows(){
var rows = document.getElementById('myTableId').getElementsByTagName('tbody')[0].rows.length;
alert( rows);
// outputs 3
}
</script>
</head>
<body>
<table id="myTableId">
<tbody>
<tr><td></td><td><input onclick="doA_Function_That_Includes_CountRows()" />
</td></tr>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
</tbody>
</table>
</body>
</html>
回答by Madara's Ghost
Try this:
尝试这个:
var rows = document.getElementById('myTableId').getElementsByTagName('tbody')[0].getElementsByTagName('tr').length;
It will count the number of <tr>
s in the <tbody>
, which in turn will be the number of rows in the table.
它将计算 中<tr>
s的数量<tbody>
,这反过来将是表中的行数。
Do note that it will NOT count all of the rows in the tableonly in the table body. If you have a <thead>
or a <tfoot>
or even a row outside of the tbody, it will not be counted.
请注意,它不会仅计算表正文中的表中的所有行。如果在 tbody 之外有 a或 a甚至一行,则不会被计算在内。<thead>
<tfoot>
回答by Felix Kling
Another way, using the rows
property [MDN]:
另一种方式,使用rows
属性[MDN]:
var num = document.getElementById('myTableId').rows.length;
If you only want to count the rows from the first tbody
element, select it first (tBody
property [docs])
如果您只想从第一个tbody
元素开始计算行数,请先选择它(tBody
属性[docs])
var num = document.getElementById('myTableId').tBodies[0].rows.length;
回答by Atanas Korchev
Here is a working implementation:
这是一个有效的实现:
var table = document.getElementById("myTableId");
var tbody = table.tBodies[0];
alert(tbody.rows.length);
And a sample jsFiddle: http://jsfiddle.net/9a6zK/
和一个示例 jsFiddle:http: //jsfiddle.net/9a6zK/
回答by Ry-
Try:
尝试:
var numberOfRows = document.getElementById('myTableId').getElementsByTagName('tbody')[0].getElementsByTagName('tr').length;