Javascript jQuery:如何计算表列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6683882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:48:24  来源:igfitidea点击:

jQuery: How to count table columns?

javascriptjquery

提问by Andrew

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

使用 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>

The total number of columns in this example is 6. How could I determine this using jQuery?

本示例中的总列数为 6。我如何使用 jQuery 确定这一点?

回答by Craig M

Here you go:

干得好:

jsFiddle

js小提琴

$(function() {
    var colCount = 0;
    $('tr:nth-child(1) td').each(function () {
        if ($(this).attr('colspan')) {
            colCount += +$(this).attr('colspan');
        } else {
            colCount++;
        }
    });
});

回答by scrappedcola

$("table").find("tr:first td").length;

I edited as I didn't realize you were counting the colspan's.

我进行了编辑,因为我没有意识到您正在计算 colspan 的数量。

If you want to include using colspan try a loop through the td's in the first row:

如果你想包括使用 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++;
   }
}

回答by Evan Moran

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

这是我认为最干净的。它处理表中的表。并且简短而简单:

$("table > tbody > tr:first > td").length

回答by Evan Moran

In POJS (Plain Old JavaScript):

在 POJS (Plain Old JavaScript) 中:

HTML:

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:

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.rowswill collect rows from every HTMLTableSectionElement(THead, TBody, and TFoot). Each section also has its own rowsHTMLCollection, so you can filter them if need be.

HTMLTableElement .rows将从每个HTMLTableSectionElement(THead、TBody 和 TFoot)收集行。每个部分也有自己的rowsHTMLCollection,因此您可以根据需要对其进行过滤。

回答by vinceh

To be robust..I'd do something like this

要robust..I'd做这样的事情

alert(numCol("table") + " is the max number of cols");

function numCol(table) {
    var maxColNum = 0;

    var i=0;
    var trs = $(table).find("tr");

    for ( i=0; i<trs.length; i++ ) {
        maxColNum = Math.max(maxColNum, getColForTr(trs[i]));
    }

    return maxColNum;
}

function getColForTr(tr) {

    var tds = $(tr).find("td");

    var numCols = 0;

    var i=0;
    for ( i=0; i<tds.length; i++ ) {
        var span = $(tds[i]).attr("colspan");

        if ( span )
            numCols += parseInt(span);
        else {
            numCols++;
        }
    }
    return numCols;
}

Just in case we have some funkiness going on between different rows.

以防万一我们在不同的行之间发生了一些有趣的事情。

回答by kdmitry

/**
 * 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.

参见行动https://jsfiddle.net/kqv7hdg5

  • Takes colspaninto account.
  • Works for nested tables.
  • Works for <thead>, <tfoot>, <tbody>.
  • Works for mix of <th>and <td>.
  • Works for malformed tables.
  • 需要colspan考虑在内。
  • 适用于嵌套表。
  • 适用于<thead>, <tfoot>, <tbody>
  • 适用于<th>和 的混合<td>
  • 适用于格式错误的表格。

Slightly modified version for those who would like to pass jQuery object instead of selector https://jsfiddle.net/5jL5kqp5.

对于那些想要传递 jQuery 对象而不是选择器https://jsfiddle.net/5jL5kqp5 的人的稍微修改版本。

回答by rainabba

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

传入一个类似于 $('foo#table') 或 $('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;
}

回答by T.J. Compton

To circumvent the td/th issue (and also fix a potential issue where attr('colspan') was giving me strings) I went with this:

为了规避 td/th 问题(并解决 attr('colspan') 给我字符串的潜在问题),我采用了以下方法:

var colspan = 0;
$('#table').find('tr:first').children().each(function(){
    var cs = $(this).attr('colspan');
    if(cs > 0){ colspan += Number(cs); }
    else{ colspan++; }
});

回答by Joe

http://jsfiddle.net/WvN9u/

http://jsfiddle.net/WvN9u/

Just paying attention to colspan attr

只关注 colspan attr

回答by doctorgu

I simplified answer of Craig M. And modified to apply to both td and th tag.

我简化了 Craig M. 的答案。并修改为适用于 td 和 th 标签。

function GetColumnCount($Table)
{
    var ColCount = 0;
    $Table.find("tr").eq(0).find("th,td").each(function ()
    {
        ColCount += $(this).attr("colspan") ? parseInt($(this).attr("colspan")) : 1;
    });

    return ColCount;
}