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

时间:2012-12-25 15:45:03

标签: jquery merge cell

请在此处查看演示。 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);
        }

但是如果表格是这样的:

    <table id="table2" style=" width: 100%;">
        <tr>
            <td rowspan="2">cell_1</td>
            <td rowspan="2">cell_2cell_5</td>
            <td>cell_3</td>
        </tr>
        <tr>
            <td>cell_6</td>
        </tr>
        <tr>
            <td>cell_7</td>
            <td>cell_8</td>
            <td>cell_9</td>
        </tr>
    </table>
当我想合并(0,0)&#34; Cell1&#34;和(2,0)&#34; Cell7&#34;,我怎样才能找到&#34;单元格7&#34;通过js代码?

希望我能解释清楚。

非常感谢。

比尔

1 个答案:

答案 0 :(得分:0)

您遇到的主要问题是,一旦将行数增加到单元格,它就会抛出行索引。如果一行中的单元格为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;

}

DEMO:http://jsfiddle.net/CqNfZ/7/

编辑:刚刚意识到我的combineSpans逻辑需要修改。将2个单元colspan加在一起会导致问题