jQuery:计算表中的行数

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

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


#1楼

我得到以下内容:

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

#2楼

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

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

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


#3楼

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

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

#4楼

我发现如果你想计算行数而不计算表中的表和行中的任何行,我发现这个工作真的很好:

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

#5楼

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

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

我认为jQuery的工作量更少。


#6楼

如果有tbody,试试这个

没有标题

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

如果有标题那么

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

请享用!!!


#7楼

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


#8楼

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

#9楼

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

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


#10楼

另外...

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

jsFiddle DEMO

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


#11楼

这是我的看法:

//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();
发布了0 篇原创文章 · 获赞 2 · 访问量 5916

猜你喜欢

转载自blog.csdn.net/asdfgh0077/article/details/104068761
今日推荐