jQuery: contar el número de filas de una tabla
Solución
Utilice un selector que selecciona todas las filas y tomar la longitud.
var rowCount = $('#myTable tr').length;
Nota: este enfoque también cuenta todos los trs de cada tabla anidada
Otros consejos
Si utiliza <tbody>
o <tfoot>
en su mesa, que tendrá que utilizar la siguiente sintaxis o que obtendrá un valor incorrecto:
var rowCount = $('#myTable >tbody >tr').length;
Como alternativa ...
var rowCount = $('table#myTable tr:last').index() + 1;
Esto asegurará que cualquier tabla-filas anidadas no están también cuentan.
Bueno, me sale de las filas de la tabla attr y obtener la longitud de esa colección:
$("#myTable").attr('rows').length;
Creo que jQuery trabaja menos.
Esta es mi opinión sobre ella:
//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();
Tengo el siguiente:
jQuery('#tableId').find('tr').index();
que necesitaba una manera de hacer esto en una declaración de AJAX, así que escribí esta pieza:
<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, esto es un ejemplo rápido, pero puede ser útil.
He encontrado que esto funcione muy bien si se desea contar filas sin contar el XIX y las filas de las tablas dentro de tablas:
var rowCount = $("#tableData > tbody").children().length;
probar esto si hay tbody
Sin Encabezado
$("#myTable > tbody").children.length
Si hay encabezado entonces
$("#myTable > tbody").children.length -1
Disfrute !!!
row_count = $('#my_table').find('tr').length;
column_count = $('#my_table').find('td').length / row_count;
var trLength = jQuery('#tablebodyID >tr').length;