jQuery:contare il numero di righe in una tabella
Domanda
Come posso contare il numero di elementi tr all'interno di una tabella utilizzando jQuery?
So che esiste un domanda simile, ma voglio solo le righe totali.
Soluzione
Utilizza un selettore che selezionerà tutte le righe e prenderà la lunghezza.
var rowCount = $('#myTable tr').length;
Nota:questo approccio conta anche tutte le tr di ogni tabella nidificata!
Altri suggerimenti
Se si utilizza <tbody>
o <tfoot>
nella tabella, si dovrà utilizzare la seguente sintassi o si otterrà un valore non corretto:
var rowCount = $('#myTable >tbody >tr').length;
In alternativa ...
var rowCount = $('table#myTable tr:last').index() + 1;
Questo farà sì che qualsiasi tavolo-righe nidificati non vengono conteggiati.
Bene, ho capito le righe attr dalla tabella e ottenere la lunghezza per la raccolta che:
$("#myTable").attr('rows').length;
Credo che jQuery funziona meno.
Ecco il mio prendere su di esso:
//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();
ho ottenuto il seguente:
jQuery('#tableId').find('tr').index();
ho bisogno di un modo per fare questo in un ritorno AJAX, così ho scritto questo pezzo:
<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>
Ovviamente questo è un esempio veloce, ma può essere utile.
Ho trovato questo lavoro davvero bene se si desidera contare le righe senza contare l'° e tutte le righe dalle tabelle all'interno di tabelle:
var rowCount = $("#tableData > tbody").children().length;
provare questo uno se c'è tbody
senza intestazione
$("#myTable > tbody").children.length
Se c'è un colpo di testa poi
$("#myTable > tbody").children.length -1
Godetevi !!!
row_count = $('#my_table').find('tr').length;
column_count = $('#my_table').find('td').length / row_count;
var trLength = jQuery('#tablebodyID >tr').length;