jQuery:如何计算表列?

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

干得好:

的jsfiddle

$(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)

  • 如果第一行包含th元素而不是td,则可能还需要调整此值.我用过('tr:last-child td') (5认同)
  • 你可以用`colCount + = this.colSpan;'替换整个IF,当它没有在HTML中设置时返回1.当DOM已经提供更好的功能时,使用jQuery毫无意义. (3认同)

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)

  • 这假设没有单元格具有`colspan`属性,并且还假设每个`tr`具有相同数量的`td`元素.那么,'th`元素呢? (6认同)

小智 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,因此您可以根据需要过滤它们.