jQuery: How to count table columns?

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

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



15条回答
  •  没有蜡笔的小新
    2020-12-28 13:31

    /**
     * Get number of columns in table.
     * @param {string} table jQuery selector
     * @param {boolean} [malformed=false] whether to inspect each row of malformed table;
     * may take some time for large tables
     * @returns {?number} number of columns in table, null if table not found.
     */
    function getTableColumnsCount(table, malformed) {
        malformed = malformed || false;
    
        var $table = $(table);
        if (!$table.length) {
            return null;
        }
    
        var rows = $table.children('thead, tfoot, tbody').children('tr');
        if (!malformed) {
            // for correct tables one row is enough
            rows = rows.first();
        }
        var maxCount = 0;
        rows.each(function () {
            var currentCount = 0;
            $(this).children('th, td').each(function () {
                currentCount += this.colSpan;
            });
            maxCount = Math.max(maxCount, currentCount);
        });
    
        return maxCount;
    }
    

    See in action https://jsfiddle.net/kqv7hdg5.

    • Takes colspan into account.
    • Works for nested tables.
    • Works for
, , .
  • Works for mix of
  • and .
  • Works for malformed tables.
  • Slightly modified version for those who would like to pass jQuery object instead of selector https://jsfiddle.net/5jL5kqp5.

    提交回复
    热议问题