考虑这个表:
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);
}
最佳答案
首先是一条评论。
对于表格单元格的遍历,请考虑利用 rows , rowIndex , cells和 cellIndex要导航的属性而不是同级属性(因为同级属性可能是文本节点,而不是元素),例如:
function getCellNext(cell) {
return cell.parentNode.cells[cell.cellIndex + 1] || null;
}
如果找不到合适的节点来返回,大多数 DOM 方法都会返回 null
。如果函数返回 null
,则 cell 是该行中的最后一个单元格。可以使用类似的策略来获取前一个单元格,或者上面或下面的单元格,例如
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。
此外,由于 rowSpan、rowIndex、cellSpan 和 cellIndex 都是 Number 类型,因此不需要对于parseInt。我也不明白为什么你在 jsbin 代码中包含 jQuery。
关于JavaScript 用于查找具有合并列和行的表格中单元格的开始和结束列索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12737083/