And*_*rew 48 javascript jquery
使用jQuery,你如何计算表中有多少列?
<script>
alert($('table').columnCount());
</script>
<table>
<tr>
<td>spans one column</td>
<td colspan="2">spans two columns</td>
<td colspan="3">spans three columns</td>
<tr>
</table>
Run Code Online (Sandbox Code Playgroud)
此示例中的列总数为6.如何使用jQuery确定这一点?
Cra*_*g M 55
干得好:
$(function() {
var colCount = 0;
$('tr:nth-child(1) td').each(function () {
if ($(this).attr('colspan')) {
colCount += +$(this).attr('colspan');
} else {
colCount++;
}
});
});
Run Code Online (Sandbox Code Playgroud)
scr*_*ola 34
$("table").find("tr:first td").length;
Run Code Online (Sandbox Code Playgroud)
我编辑,因为我没有意识到你在计算colspan的.
如果你想使用colspan包含,请尝试在第一行中的td循环:
var cols = $("table").find("tr:first td");
var count = 0;
for(var i = 0; i < cols.length; i++)
{
var colspan = cols.eq(i).attr("colspan");
if( colspan && colspan > 1)
{
count += colspan;
}else{
count++;
}
}
Run Code Online (Sandbox Code Playgroud)
Eva*_*ran 31
这是我认为最干净的.它处理表中的表.并且简短而简单:
$("table > tbody > tr:first > td").length
Run Code Online (Sandbox Code Playgroud)
小智 5
在POJS(Plain Old JavaScript)中:
HTML:
<table id="foo">
<thead></thead>
<tbody>
<tr>
<td>1</td>
<td colspan="2">2</td>
<td colspan="3">3</td>
</tr>
</tbody>
<tfoot></tfoot>
</table>
Run Code Online (Sandbox Code Playgroud)
JS:
var foo = document.getElementById("foo"), i = 0, j = 0, row, cell, numCols = 0;
//loop through HTMLTableElement.rows (includes thead, tbody, tfoot)
for(i;i<foo.rows.length;i++)
{
row = foo.rows[i];
//loop through HTMLTableRowElement.cells
for(j = 0;j<row.cells.length;j++)
{
cell = row.cells[j];
numCols += cell.colSpan;
cell = null;
}
row = null;
}
alert(numCols) //6;
Run Code Online (Sandbox Code Playgroud)
HTMLTableElement .rows将从每个HTMLTableSectionElement(THead,TBody和TFoot)中收集行.每个部分也有自己的rowsHTMLCollection,因此您可以根据需要过滤它们.