Pergunta

Como faço para contar o número de elementos tr dentro de uma tabela usando jQuery?

Eu sei que há um pergunta semelhante , mas eu só quero as linhas totais.

Foi útil?

Solução

Use um seletor que irá selecionar todas as linhas e tirar o comprimento.

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

Nota: esta abordagem também conta todos os trs de cada tabela aninhada

Outras dicas

Se você usar <tbody> ou <tfoot> em sua mesa, você terá que usar a seguinte sintaxe ou você vai ter um valor incorreto:

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

Como alternativa ...

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

jsFiddle DEMONSTRA

Isto irá assegurar que qualquer mesa de linhas aninhados não são também contados.

Bem, eu recebo as linhas attr da tabela e obter o comprimento para essa coleção:

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

Eu acho que jQuery trabalha menos.

Aqui está a minha opinião sobre ele:

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

USO:

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

Eu tenho o seguinte:

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

Eu precisava de uma maneira de fazer isso em um retorno AJAX, então eu escrevi esta peça:

<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>

Obviamente este é um exemplo rápido, mas pode ser útil.

Encontrei este trabalho muito bem se você quiser contar linhas sem contar o th e quaisquer linhas de tabelas dentro de tabelas:

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

tente este se houver tbody

Sem cabeçalho

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

Se houver cabeçalho, em seguida,

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

Aproveite !!!

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

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top