2012-09-22 36 views
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> 

回答

3

根據需要,無需.each()循環,只使用after()

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

The demo

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

Working Fiddle

+0

這是給所有的表中的行之和,其中(4),兩個表後。 –

+0

是啊..我第一次沒有正確地閱讀yr問題..正確的修改然後..如果您將函數傳遞給'後'在該代碼..它會給出正確的結果。 –

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"); 
}); 

Working DEMO

更新你可以做到這一點的,當然不太行,我把它分成m使用評論使其更清楚。你可以寫:

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

這是怎麼回事?

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

編輯

到最後表後得到兩個表總:

$('table:last').after($('tr').length + " rows found.") 
+0

返回所有表中的行的總和而不是每個表中的行的總和。 –

+0

對不起。誤解了你的第一篇文章。嘗試這個? $('table:last')。after($('tr')。length +「rows found。」)' – mbinette

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 Fiddle demo

相關問題