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

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


当前回答

或者……

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

jsFiddle演示

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

其他回答

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

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

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

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

以下是我的看法:

//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();
row_count =  $('#my_table').find('tr').length;
column_count =  $('#my_table').find('td').length / row_count;

我需要一种在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>

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