JavaScript,用于查找具有合并列和行的表中单元格的起始列索引和结束列索引



考虑下表:

http://jsbin.com/esikac/1/edit

请注意,每个单元格都有一个值对,如"x-y",x是开始列索引,y是结束列索引(在这种情况下,列是列之间的行,而不是列本身,从零开始)。希望这是有道理的。

我需要的是一些javascript,它将接受一个单元格(一个td元素),并为我提供它的开始和结束列索引,就像在我的示例表中一样。假设我有一个函数getColumnBounds,它将td元素作为参数。如果我调用它并传递表右上角的td,它会给我"3-5"(当然不是通过阅读里面的文本,而是通过计算)。

到目前为止,这就是我所拥有的,但如果在添加合并行时失败:

function getColumnBounds(td) {
function colSpan(col) {
return parseInt((col && col.nodeType == 1 && element.nodeName.match(/t[dh]/i)) ? (col.getAttribute("colSpan") || 1) : 0);
}
function endIndex(element) {
var colPos = colSpan(element);
while(element) {
element = element.previousSibling;
colPos += colSpan(element);
}
return colPos;
}
var startIndex = endIndex(td.previousSibling);
var endIndex = endIndex(td);
return ("" + startIndex + "-" + endIndex);
}

首先是一个注释。

对于表单元格的遍历,请考虑利用行、rowIndex、单元格和cellIndex属性进行导航,而不是同级(因为同级可能是文本节点,而不是元素),例如:

function getCellNext(cell) {
return cell.parentNode.cells[cell.cellIndex + 1] || null;
}

如果找不到合适的节点返回,大多数DOM方法都会返回null。如果函数返回null,则单元格是行中的最后一个单元格。类似的策略可以用于获得前一个单元格,或者上面或下面的单元格,例如

function getCellAbove(cell) {
var row = cell.parentNode;
var table = row.parentNode.parentNode; // may use tableSection instead
var rowAbove = table.rows[row.rowIndex - 1];
return rowAbove? row.cells[cell.cellIndex] : null;
}

使用表上的单个侦听器,以下内容返回特定单元格的列和行范围:

// Get the cell and row range of a particular cell
function getCellRange(cell) {
var colRange = cell.cellIndex + '-' + (cell.cellIndex + cell.colSpan - 1);
var row = cell.parentNode;
var rowRange = row.rowIndex + '-' + (row.rowIndex + cell.rowSpan - 1);
return [colRange, rowRange];
}
// Helper functions
function upTo(el, tagName) {
tagName = tagName.toLowerCase();
while (el && el.nodeName.toLowerCase() != tagName) {
el = el.parentNode;
}
return el || null;
}
// Call getCellRange from an event
function showCellRange(e) {
var target = e.target || e.srcElement;
var cell = upTo(target, 'td');
return cell? getCellRange(cell) : null;
}

侦听器(和表)是:

<table onclick="alert(showCellRange(event));">
<tr>
<td colspan="2">0-2
<td rowspan="2">2-3
<td colspan="2">3-5
<tr>
<td>0-1
<td>1-2
<td>3-4
<td>4-5
<tr>
<td>0-1
<td colspan="2">1-3
<td>3-4
<td>4-5
<tr>
<td>0-1
<td colspan="3">1-4
<td>4-5
<tr>
<td>0-1
<td>1-2
<td colspan="2">2-4
<td>4-5
</table>

我认为你的范围不正确。如果第一个单元格的colspan为2,则其范围为0-1,而不是0-2。

此外,由于rowSpanrowIndexcellSpancellIndex都是Number类型,因此不需要parseInt。我也不明白为什么在jsbin代码中包含jQuery。

最新更新