javascript 如何使用 DOM 查找表的列数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13819788/
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
How to find a table's column count using the DOM?
提问by mano
For row count using DOM, we have tablename.rows.length to get number of rows, but we don't have 'cols.length' for column count.
对于使用 DOM 的行数,我们有 tablename.rows.length 来获取行数,但我们没有 'cols.length' 用于列数。
How can we find the number of columns (only using the DOM)?
我们如何找到列数(仅使用 DOM)?
回答by Tim Down
I would use the table's rows
property and the first row's cells
property and total the colSpan
property of each cell in the row. This will work in all major browsers back to IE 4 and should be pretty fast.
我会使用表格的rows
属性和第一行的cells
属性,并合计行colSpan
中每个单元格的属性。这将适用于所有主要浏览器回到 IE 4 并且应该非常快。
Demo: http://jsfiddle.net/Gtdru/
演示:http: //jsfiddle.net/Gtdru/
Code:
代码:
function getTableColumnCount(table) {
var columnCount = 0;
var rows = table.rows;
if (rows.length > 0) {
var cells = rows[0].cells;
for (var i = 0, len = cells.length; i < len; ++i) {
columnCount += cells[i].colSpan;
}
}
return columnCount;
}
回答by senK
I think you can use cells to calculate the column, assuming that the number of column of first row will be same for all
我认为您可以使用单元格来计算列,假设第一行的列数对于所有人都相同
tablename.rows[0].cells.length;
回答by Denys Séguret
There isn't such a concept in the DOM.
DOM 中没有这样的概念。
You could try and count the max number of td
and th
in tr
:
您可以尝试计算td
和th
in的最大数量tr
:
var max = 0;
$('#tableId tr').each(function(){max=Math.max(max, $('td,th', this).length)});
If you want to take into account the colspan, it's a little heavier :
如果你想考虑 colspan,它会重一点:
var max = 0;
$('#tableId tr').each(function(){
var inTr = 0;
$('td,th', this).each(function() { inTr += parseInt($(this).attr('colspan')) || 1;});
max = Math.max(max,inTr);
});
回答by italo.portinho
This will work with complex table headers :
这将适用于复杂的表头:
$($('#table_id_here tbody tr')[0]).find('td').length
回答by Machado
A very simple way to get the number of possible cols in any table is using the following (vanillaJS) function:
获取任何表中可能的列数的一种非常简单的方法是使用以下 (vanillaJS) 函数:
/**
* Calculates the number of columns based on any row using colSpan attribute.
*
* @param {HTMLElement} table : The table element to be count.
*
* @return {int} The number of columns this table has.
*/
var getTableColSpan = function getTableColSpan(table) {
var colSpan = 0; // initialize counter
var trs = table.querySelectorAll('tr'); // get firt tr cells.
for (var j = 0; j < trs.length; j++) {
var tr = trs[j];
var tds = tr.cells;
var trColSpan = 0; // initialize counter
// loops between columns and gets each one's colSpan
for (var i = 0; i < tds.length; ++i) {
trColSpan += tds[i].colSpan;
}
colSpan = trColSpan > colSpan ? trColSpan : colSpan;
}
return colSpan;
};