Javascript 获取 HTML 表格中的行数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11742946/
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
Get the number of rows in a HTML table
提问by Code Ratchet
I've browsed the Internet looking for an answer on this but I can't find a solution. I want to count the amount of rows my HTML table has in when a link button is pressed. Can someone help me out please?
我浏览了 Internet 寻找有关此问题的答案,但找不到解决方案。我想计算按下链接按钮时 HTML 表中的行数。有人可以帮我吗?
This is what I have so far:
这是我到目前为止:
$('#HypSelectAll').click(function () {
var count = $('#gvPerformanceResult').children().length;
for (i = 0; i < count; i++) {
alert(i);
}
});
But some reason it returns 0 even though I have about 12 rows in my table? I've checked my ID name and it's correct.
但是某些原因即使我的表中有大约 12 行它也会返回 0?我检查了我的 ID 名称,它是正确的。
回答by treeFan
var x = document.getElementById("myTable").rows.length;
回答by John Conde
Try:
尝试:
var count = $('#gvPerformanceResult tr').length;
回答by Al_th
The following code assumes that your table has the ID 'MyTable'
<script language="JavaScript"> <!-- var oRows = document.getElementById('MyTable').getElementsByTagName('tr'); var iRowCount = oRows.length; alert('Your table has ' + iRowCount + ' rows.'); //--> </script>
以下代码假定您的表具有 ID 'MyTable'
<script language="JavaScript"> <!-- var oRows = document.getElementById('MyTable').getElementsByTagName('tr'); var iRowCount = oRows.length; alert('Your table has ' + iRowCount + ' rows.'); //--> </script>
Answer taken from : http://www.delphifaq.com/faq/f771.shtml, which is the first result on google for the query : "Get the number of rows in a HTML table" ;)
答案取自:http: //www.delphifaq.com/faq/f771.shtml,这是 google 上查询的第一个结果:“获取 HTML 表中的行数”;)
回答by Jukka K. Korpela
In the DOM, a tr
element is (implicitly or explicitly) a child of tbody
, thead
, or tfoot
, not a child of table
(hence the 0 you got). So a general answer is:
在DOM中,一个tr
元素(或明或暗地)的孩子tbody
,thead
或者tfoot
,不是一个孩子table
(因此你得到了0)。所以一般的答案是:
var count = $('#gvPerformanceResult > * > tr').length;
This includes the rows of the table but excludes rows of any inner table.
这包括表的行,但不包括任何内部表的行。
回答by Mark Broadhurst
Well it depends on what you have in your table.
嗯,这取决于你的桌子上有什么。
its one of the following If you have only one table
它是以下之一 如果您只有一张桌子
var count = $('#gvPerformanceResult tr').length;
If you are concerned about sub tables but this wont work with tbody and thead (if you use them)
如果您担心子表,但这不适用于 tbody 和 thead(如果您使用它们)
var count = $('#gvPerformanceResult>tr').length;
Where by this will work (but is quite frankly overkill.)
这将在哪里工作(但坦率地说是矫枉过正。)
var count = $('#gvPerformanceResult>tbody>tr').length;