jQuery: How to count table columns?

前端 未结 15 1392
天命终不由人
天命终不由人 2020-12-28 13:20

Using jQuery, how would you figure out how many columns are in a table?



相关标签:
15条回答
  • 2020-12-28 13:46

    This is the cleanest in my opinion. It handles tables within tables. And is short and simple:

    $("table > tbody > tr:first > td").length
    
    0 讨论(0)
  • 2020-12-28 13:48

    In 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>
    

    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;
    

    HTMLTableElement.rows will collect rows from every HTMLTableSectionElement (THead, TBody, and TFoot). Each section also has its own rows HTMLCollection, so you can filter them if need be.

    0 讨论(0)
  • 2020-12-28 13:48

    Pass in a table with something like $('foo#table') or $('table:first')

    function getColumnCount(e) { //Expects jQuery table object
        var c= 0;
        e.find('tbody tr:first td').map(function(i,o) { c += ( $(o).attr('colspan') === undefined ? 1 : parseInt($(o).attr('colspan')) ) } );
        return c;
    }
    
    0 讨论(0)
提交回复
热议问题