如何使用 jQuery 计算表中 tr 元素的数量?
我知道有一个类似的问题,但我只想要总行数。
使用将选择所有行并获取长度的选择器。
var rowCount = $('#myTable tr').length;
注意:这种方法还计算每个嵌套表的所有 trs!
如果你在你的表中使用<tbody>
or <tfoot>
,你必须使用下面的语法,否则你会得到一个不正确的值:
var rowCount = $('#myTable >tbody >tr').length;
好吧,我从表中获取 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;
};
用法:
var rowCount = $('#productTypesTable').rowCount();
我得到以下信息:
jQuery('#tableId').find('tr').index();
如果有 tbody 试试这个
没有标题
$("#myTable > tbody").children.length
如果有标题那么
$("#myTable > tbody").children.length -1
享受!!!
我需要一种在 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>
显然这是一个简单的例子,但它可能会有所帮助。
如果您想计算行而不计算 th 和表内表中的任何行,我发现这非常有效:
var rowCount = $("#tableData > tbody").children().length;
row_count = $('#my_table').find('tr').length;
column_count = $('#my_table').find('td').length / row_count;
var trLength = jQuery('#tablebodyID >tr').length;
document.getElementById("myTable").rows.length;