Answers:
使用选择器将选择所有行并采用长度。
var rowCount = $('#myTable tr').length;
注意:此方法还计算每个嵌套表的所有trs!
如果在表中使用<tbody>
或<tfoot>
,则必须使用以下语法,否则将获得不正确的值:
var rowCount = $('#myTable >tbody >tr').length;
var rowCount = $('table#myTable tr:last').index() + 1;
<thead>
行和嵌套表行。真好 jsfiddle.net/6v67a/1576
<td>
具有内部表,则返回该表的行数!!jsfiddle.net/6v67a/1678
这是我的看法:
//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();
如果有身体请尝试这个
没有标题
$("#myTable > tbody").children.length
如果有标题,那么
$("#myTable > tbody").children.length -1
请享用!!!
<thead>
之前<tbody>
。因此,如果表格是根据标准正确设计的,则不需要-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>
显然,这是一个简单的示例,但可能会有所帮助。