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>
Общее количество столбцов в этом примере - 6. Как я могу определить это с помощью jQuery?
Ответы
Ответ 1
Здесь вы идете:
jsFiddle
$(function() {
var colCount = 0;
$('tr:nth-child(1) td').each(function () {
if ($(this).attr('colspan')) {
colCount += +$(this).attr('colspan');
} else {
colCount++;
}
});
});
Ответ 2
$("table").find("tr:first td").length;
Я отредактировал, так как не понимал, что вы считаете colspan's.
Если вы хотите включить использование 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++;
}
}
Ответ 3
Это самое чистое, на мой взгляд. Он обрабатывает таблицы в таблицах. И коротко и просто:
$("table > tbody > tr:first > td").length
Ответ 4
В POJS (обычный старый 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 будет собирать строки из каждого HTMLTableSectionElement (THead, TBody и TFoot). Каждый раздел также имеет свой собственный rows
HTMLCollection, поэтому вы можете их фильтровать, если это необходимо.
Ответ 5
Быть надежным. Я сделал что-то вроде this
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;
}
На всякий случай у нас есть какая-то забава между разными строками.
Ответ 6
http://jsfiddle.net/WvN9u/
Просто обращая внимание на colspan attr
Ответ 7
Перейдите в таблицу с чем-то вроде $('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;
}
Ответ 8
Чтобы обойти проблему 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++; }
});
Ответ 9
Вам нужно установить идентификатор в строку заголовка:
<table>
<tr id="headerRow">
<td>spans one column</td>
<td colspan="2">spans two columns</td>
<td colspan="3">spans three columns</td>
</tr>
</table>
И затем вы можете использовать следующую функцию:
function getColumnCount(headerRowId) {
var columnCount = 0;
$('#' + headerRowId + ' > td').each(function() {
var colspanValue = $(this).attr('colspan');
if (colspanValue == undefined) {
columnCount++;
} else {
columnCount = columnCount + parseInt(colspanValue);
}
});
return columnCount;
}
Ответ 10
Я упростил ответ Крейга М.
И изменен для применения к тегу 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;
}
Ответ 11
var foo = document.getElementById("price-test-table")
foo.tBodies["0"].firstElementChild.children.length
- Дайте вашей таблице идентификационное имя
- Предположим, что ваши строки имеют одинаковое количество столбцов, и у вас есть тело таблицы.
- Используйте вышеприведенный код, который, по моему мнению, является самым простым здесь, похожим на первый ответ
но предоставляет немного больше деталей
Ответ 12
function(){
num_columns = 0;
$("table td]").each(function(){
num_columns = num_columns + ($(this).attr('colspan') == undefined ? 1 : $(this).attr('colspan'));
});
return num_columns;
}