JavaScript/jQuery如何计算tbody中的行数

3
我是一个有用的助手,可以为您进行文本翻译。
我正在尝试制作一个简单的while循环来计算表格#offices中行的数量,但是我不知道为什么这不起作用,而警报一直返回0...
html:
<table id="offices" class="table table-striped">
    <caption class="text-left">
      <p class="lead">Current List of Offices</p>
    </caption>
    <thead>
        <tr>
            <th>Office Name</th>
            <th>Office abrev.</th>
            <th>Display Order</th>
            <th>Edit</th>
            <!-- TMPL_UNLESS is_agent -->
            <th>Delete</th>
            <!-- /TMPL_UNLESS -->
        </tr>
    </thead>
    <tbody>
    <!-- TMPL_LOOP Office_loop -->
    <tr>
        <td><!-- TMPL_VAR office_name --></td>
        <td><!-- TMPL_VAR short_name --></td>
        <td><!-- TMPL_VAR sequence_number ESCAPE=0 --></td>
        <td><a href="/office/edit/<!-- TMPL_VAR office_id -->"><i class="fa fa-edit"></i> Edit Office</a></td>
        <!-- TMPL_UNLESS is_agent GLOBAL=1 -->
        <td><a href="/office/delete/<!-- TMPL_VAR office_id -->"><i class="fa fa-trash-o"></i> Delete Office</a></td>
        <!-- /TMPL_UNLESS -->
    </tr>
    <!-- /TMPL_LOOP -->
    </tbody>
</table>

js/jquery:

var rowCount = $("#offices > tr").length;
alert(rowCount);
var i = 0;
while ( ++i <= rowCount ) {
    console.log( "counting rows: " + i );
}

使用 $("#offices tr") - Satpal
@Satpal 我需要针对 tbody tr 进行特定的目标,以便我不计算 thead 行。 - TEN Design
在(document).ready中仍然没有。 - TEN Design
然后使用 $("#offices > tbody > tr") - Satpal
3个回答

11

试试这个:

$('#tabId tbody').find('tr').length;

3

您可以使用

var rowCount = $('#tableId tr').length;

1
使用$("#offices tbody tr")代替$("#offices > tr") >表示查找直接子元素。

1
是的,$("#offices tbody tr")有效。 - TEN Design

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接