如何知道具有合并行或列的html表的实际列和行索引

请在此处查看演示。 http://jsfiddle.net/wgstudio/CqNfZ/2/

我想在一个html talbe中合并单元格(0,0)和单元格(1,0),它适用于常规表。

代码如下。

function() { var table = $("#table1"); var rowIndex = 0; var colIndex = 0; var actionCell =$($(table.children().children()[rowIndex]).children()[colIndex]); //Cell1 var tr = table.children().children()[rowIndex + 1]; var toBeRemoved = $($(tr).children()[colIndex]);//Cell4 toBeRemoved.remove(); rowSpan = toBeRemoved.attr("rowSpan") == undefined ? 1 : parseInt(toBeRemoved.attr("rowSpan"), 10); actionCell.attr("rowspan", (actionCell.attr("rowSpan") == undefined ? 1 : parseInt(actionCell.attr("rowSpan"), 10)) + rowSpan); } 

但如果表格是这样的:

  
cell_1 cell_2cell_5 cell_3
cell_6
cell_7 cell_8 cell_9

(0,0)(0,1)是合并的单元格,当我想合并(0,0)“Cell1”和(2,0)“Cell7”时,如何通过js代码找到“cell 7”?

希望我能解释清楚。

非常感谢你。

法案

您遇到的主要问题是,一旦将行数增加到单元格,它就会抛出行索引。 如果一行中的单元格具有rowspan=3 ,则同一列中下一个单元格的row indexcurrentRowIndex + 3

这是您需要的一个非常好的开始。

 $("#button2").click(function() { /* hard code a cell to start with*/ var actionCell = $('td:first'); var toBeRemoved = findNextCell(actionCell); combineSpans( actionCell, toBeRemoved) /* remove merged*/ toBeRemoved.remove(); }); function combineSpans( actionCell, toBeRemoved){ var actionSpans = getCellSpans(actionCell); var nextSpans = getCellSpans(toBeRemoved); /* add colspan and rowspan for both cells to apply to actionCell*/ var newSpans = { rowspan: actionSpans.rowSpan + nextSpans.rowSpan, colspan: actionSpans.colSpan + nextSpans.colSpan } /* adjust actionCell colspan/rowspan*/ actionCell.attr(newSpans); } function findNextCell($cell) { var cellIndex = $cell.index(); var rowSpan = $cell.attr("rowspan") || 1; var rowIndex = $cell.closest('tr').index(); var nextRow = $cell.closest('table').find('tr').eq(1 * rowSpan + rowIndex); return nextRow.find('td').eq(cellIndex); } function getCellSpans($cell) { var obj = {} obj.rowSpan = parseInt($cell.attr("rowspan") || 1, 10); obj.colSpan = parseInt($cell.attr("colspan") || 1, 10); return obj; } 

演示: http : //jsfiddle.net/CqNfZ/7/

编辑 :刚刚意识到我的combineSpans逻辑需要修改。 添加2个细胞colspan将导致问题