2

我在同一页面上有多个表格,并希望添加每个表格的行显示计数,如下所示。我尝试了一些东西,但它给出了所有表格行的总数。

<table>
 <tr>
   <td>Some data</td>
   <td>More data</td>
 </tr>
 <tr>
   <td>Some data</td>
   <td>More data</td>
 </tr>
</table>

<table>
 <tr>
   <td>Some data</td>
   <td>More data</td>
 </tr>
 <tr>
   <td>Some data</td>
   <td>More data</td>
 </tr>
</table>

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
 $().ready(function(){

  //I want to add a line after each table showing each table row count
  $("table").after(??? + " rows found.");
 });
</script>
4

5 回答 5

4
$("table").each(function(){
    $(this).after($(this).find('tr').length + " rows found.");    
})

工作小提琴

于 2012-09-22T09:19:14.587 回答
3

根据需要,不.each()使用循环,仅使用after().

$("table").after(function(){
    return $('tr', this).length + " rows found.";    
});

演示

于 2012-09-22T09:43:41.080 回答
3

您可以像这样很容易地获得行数:

// loop over all tables
$("table").each(function(){ 
    // get number of rows, uses jQuery's context parameters to speed things up
    // (it is apparently somewhat faster than using 'find' in most cases)
    var nrOfRows = $("tr", this).length;

    $(this).after(nrOfRows + " rows found");
});

工作演示

更新您当然可以用更少的行来完成,我将其拆分以使用注释使其更清晰。你可以写:

$("table").each(function(){ 
    $(this).after($("tr", this).length + " rows found");
});
于 2012-09-22T09:20:33.343 回答
3

那这个呢?

$("table").each(function(){
    $(this).after($(this).find('tr').length + " rows found.")
});

编辑

要在最后一个表之后从两个表中获取总数:

$('table:last').after($('tr').length + " rows found.")
于 2012-09-22T09:20:43.427 回答
1

我建议:

​$('table tbody').each(
    function(){
        var tfoot = $('<tfoot />', {'class' : 'rowSummary'}).insertBefore($(this)),
            tr = $('<tr />').appendTo(tfoot),
            len = $(this).find('tr').length,
            cell = $('<td />',{'colspan' : '2' }).text(len).appendTo(tr);
    });​​​​​​​​​​​​​

JS 小提琴演示

于 2012-09-22T09:21:51.763 回答