528

如何使用 jQuery 计算表中 tr 元素的数量?

我知道有一个类似的问题,但我只想要总行数。

4

12 回答 12

1027

使用将选择所有行并获取长度的选择器。

var rowCount = $('#myTable tr').length;

注意:这种方法还计算每个嵌套表的所有 trs!

于 2009-07-19T14:05:34.133 回答
196

如果你在你的表中使用<tbody>or <tfoot>,你必须使用下面的语法,否则你会得到一个不正确的值:

var rowCount = $('#myTable >tbody >tr').length;
于 2010-02-18T22:21:37.437 回答
50

或者...

var rowCount = $('table#myTable tr:last').index() + 1;

jsFiddle 演示

这将确保不计算任何嵌套的表行。

于 2011-10-21T16:20:35.603 回答
33

好吧,我从表中获取 attr 行并获取该集合的长度:

$("#myTable").attr('rows').length;

我认为 jQuery 工作较少。

于 2010-04-05T03:32:28.430 回答
18

这是我的看法:

//Helper function that gets a count of all the rows <TR> in a table body <TBODY>
$.fn.rowCount = function() {
    return $('tr', $(this).find('tbody')).length;
};

用法:

var rowCount = $('#productTypesTable').rowCount();
于 2012-03-12T04:58:47.100 回答
12

我得到以下信息:

jQuery('#tableId').find('tr').index();
于 2012-05-31T15:36:28.157 回答
9

如果有 tbody 试试这个

没有标题

$("#myTable > tbody").children.length

如果有标题那么

$("#myTable > tbody").children.length -1

享受!!!

于 2015-07-14T13:34:13.067 回答
7

我需要一种在 AJAX 返回中执行此操作的方法,所以我写了这篇文章:

<p id="num_results">Number of results: <span></span></p>

<div id="results"></div>

<script type="text/javascript">
$(function(){
    ajax();
})

//Function that makes Ajax call out to receive search results
var ajax = function() {
    //Setup Ajax
    $.ajax({
        url: '/path/to/url', //URL to load
        type: 'GET', //Type of Ajax call
        dataType: 'html', //Type of data to be expected on return
        success: function(data) { //Function that manipulates the returned AJAX'ed data
            $('#results').html(data); //Load the data into a HTML holder
            var $el = $('#results'); //jQuery Object that is holding the results
            setTimeout(function(){ //Custom callback function to count the number of results
                callBack($el);
            });
        }
    });
}

//Custom Callback function to return the number of results
var callBack = function(el) {
    var length = $('tr', $(el)).not('tr:first').length; //Count all TR DOM elements, except the first row (which contains the header information)
    $('#num_results span').text(length); //Write the counted results to the DOM
}
</script>

显然这是一个简单的例子,但它可能会有所帮助。

于 2011-05-09T14:30:35.570 回答
7

如果您想计算行而不计算 th 和表内表中的任何行,我发现这非常有效:

var rowCount = $("#tableData > tbody").children().length;
于 2014-09-09T11:14:47.217 回答
4
row_count =  $('#my_table').find('tr').length;
column_count =  $('#my_table').find('td').length / row_count;
于 2018-03-10T04:47:28.230 回答
1

var trLength = jQuery('#tablebodyID >tr').length;

于 2015-09-03T03:24:54.627 回答
0

document.getElementById("myTable").rows.length;

于 2021-08-26T01:48:46.067 回答