JQuery - 获取表体中的行数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2819522/
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
JQuery - Get the number of rows in a table body
提问by user336786
I have an HTML table that is defined as follows:
我有一个定义如下的 HTML 表:
<table id="myTable" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Birth Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Smith</td>
<td>03-11-1980</td>
</tr>
</tbody>
</table>
I want to understand how to determine how many rows are in thetbody
portion of my table, instead of the table in general. How do I use JQuery to determine how many rows are in the tbody portion of a table?
我想了解如何确定我的 table 部分中有多少行,而不是一般的 table。如何使用 JQuery 确定表的 tbody 部分中有多少行?tbody
Thank you!
谢谢!
回答by SLaks
回答by Scott Ivey
Have you tried...
你有没有尝试过...
$("#myTable tbody tr").length
UPDATE: as mentioned in the comment - the above example doesn't account for nested tables. If you want to cover that as well, you'd want to use the parent/child selectorsinstead.
更新:如评论中所述 - 上面的示例没有考虑嵌套表。如果你也想涵盖这一点,你会想改用父/子选择器。
$("#myTable > tbody > tr").length
回答by John
var amountOfRows = $("#myTable tbody tr").length;
alert(amountOfRows);
The variable amountOfRows will hold the number of rows. You can also use $("#myTable tbody tr").size But that is a shortcut for .length
变量 amountOfRows 将保存行数。您也可以使用 $("#myTable tbody tr").size 但这是 .length 的快捷方式
If used on nested tables see SLaks answer
如果在嵌套表上使用,请参阅 SLaks 答案
回答by mmv_sat
use this if you don't have a table id or just want to generalize tables
如果您没有表 ID 或只想概括表,请使用此选项
$('table.table').find('tbody').children().length;
回答by Fabio
There are several different ways you can do this, here are two of them
有几种不同的方法可以做到这一点,这里有两种
var totalRows = ?$('tbody > tr > td').?????length
var totalRows2 = $('tbody').find('td').length
The var totalRowsand totalRows2will have the number of 'td'
that are inside tbody
var totalRows和totalRows2将有'td'
里面的数字tbody