具有多个 <tr> 的 table 中的可靠列数
Reliable column count in a table with multiple <tr>'s
我有一个table大概是这样的:
<table>
<thead>
<tr>
<th>Mars</th>
<th>Venus</th>
<th>Jupiter</th>
<th>Pluto</th>
</tr>
<tr>
<th scope="col">Produced</th>
<th scope="col">Sold</th>
<th scope="col">Produced</th>
<th scope="col">Sold</th>
</tr>
</thead>
<tr>
<td>1</td>
<td>50,000</td>
<td>30,000</td>
<td>100,000</td>
<td>80,000</td>
</tr>
<tr>
<td>2</td>
<td>10,000</td>
<td>5,000</td>
<td>12,000</td>
<td>9,000</td>
</tr>
</table>
忽略数据——它真的很糟糕。
我正在计算 thead
中最后一个 tr
下 th
的数量。
使用 jQuery,我执行了以下 $([=16=]).find('thead th').length
以获得列数,但在我的应用程序中,我会得到 8,因为从技术上讲 th
在 thead
。我想要一个解决方案,我只计算最后一个 tr
中的所有 th
(假设我的 table 在 thead
中有多个 tr
)。
我主要是想找到一种可靠的方法来计算 table 中的列数。
编辑:
这是一个 CodePen:http://codepen.io/anon/pen/OWByqW
使用直接子选择器:https://api.jquery.com/child-selector/
最后一个选择器:https://api.jquery.com/last-selector/
$([=10=]).find('thead > tr :last > th').length
这很容易。
var ths = document.querySelector('thead tr:last-child');
console.log(ths.childElementCount);
我有一个table大概是这样的:
<table>
<thead>
<tr>
<th>Mars</th>
<th>Venus</th>
<th>Jupiter</th>
<th>Pluto</th>
</tr>
<tr>
<th scope="col">Produced</th>
<th scope="col">Sold</th>
<th scope="col">Produced</th>
<th scope="col">Sold</th>
</tr>
</thead>
<tr>
<td>1</td>
<td>50,000</td>
<td>30,000</td>
<td>100,000</td>
<td>80,000</td>
</tr>
<tr>
<td>2</td>
<td>10,000</td>
<td>5,000</td>
<td>12,000</td>
<td>9,000</td>
</tr>
</table>
忽略数据——它真的很糟糕。
我正在计算 thead
中最后一个 tr
下 th
的数量。
使用 jQuery,我执行了以下 $([=16=]).find('thead th').length
以获得列数,但在我的应用程序中,我会得到 8,因为从技术上讲 th
在 thead
。我想要一个解决方案,我只计算最后一个 tr
中的所有 th
(假设我的 table 在 thead
中有多个 tr
)。
我主要是想找到一种可靠的方法来计算 table 中的列数。
编辑:
这是一个 CodePen:http://codepen.io/anon/pen/OWByqW
使用直接子选择器:https://api.jquery.com/child-selector/ 最后一个选择器:https://api.jquery.com/last-selector/
$([=10=]).find('thead > tr :last > th').length
这很容易。
var ths = document.querySelector('thead tr:last-child');
console.log(ths.childElementCount);