如何计算使用jQuery表内TR元件的数目?

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

有帮助吗?

解决方案

使用一种选择器,将选择的所有行,并采取长度。

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

请注意:这个方法也算每个嵌套表的所有TRS

其他提示

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

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

...替代地

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

的jsfiddle演示

这将确保任何嵌套表行未也计算在内。

好了,我从表中的ATTR行,并得到该集合长度:

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

我认为jQuery的效果欠佳。

下面是我对此采取:

//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;
};

<强> USAGE:

var rowCount = $('#productTypesTable').rowCount();

我得到了以下内容:

jQuery('#tableId').find('tr').index();

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

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

我发现这不统计该日和表内表中的任何行工作非常好,如果你要算行:

var rowCount = $("#tableData > tbody").children().length;
  

尝试这一个,如果有TBODY

无头

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

如果有标题然后

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

<强> 享受!!!

row_count =  $('#my_table').find('tr').length;
column_count =  $('#my_table').find('td').length / row_count;

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top