How can I find each table cell's “visual location” using jQuery?

后端 未结 5 793
小蘑菇
小蘑菇 2020-12-09 05:56

I have a HTML table that contains both ROWSPANs and COLSPANs.

How can I find each cell\'s \"visual location\" using jQuery?

For example, here\'s a visual rep

5条回答
  •  生来不讨喜
    2020-12-09 06:29

    your solution        my proposed table design
    +--+--+--+--+--+     +--+--+--+--+--+
    |  |A |B |C |D |     |  |A |B |C |D |     length 5 vs 5
    +--+--+--+--+--+     +--+--+--+--+--+
    |1 |A1|B1   |D1|     |1 |A1|B1|//|D1|
    +--+--+--+--+  +     +--+--+--+--+--+
    |2 |A2   |C2|  |     |2 |A2|//|C2|//|     length 3 vs 5
    +--+     +--+  +     +--+--+--+--+--+
    |3 |     |C3|  |     |3 |//|//|C3|//|
    +--+--+--+--+--+     +--+--+--+--+--+
    |4 |A4|B4|C4|D4|     |4 |A4|B4|C4|D4|
    +--+--+--+--+--+     +--+--+--+--+--+
    |XYZ           |     |XY|//|//|//|//|     length 1 vs 5
    +--+--+--+--+--+     +--+--+--+--+--+
    
    // cells labeled '//' above have this class
    
    td.stuffing { display: none; }
    

    Do you see what I did there?

    This is the third row, for example:

    
      2
      A2
      
      C2
      
    
    

    Now the function to retrieve correct index is very simple.

    function getCellLocation(cell) {
        return {row:cell.parentNode.rowIndex, cell:cell.cellIndex}
    }
    


    And here is a bonus. If you were to access a hidden cell, this will automatically traverse to the correct one, which spans over those hidden.

    function getSmartCell(table, row, col) {
        var cell = table.rows[row].cells[col];
        if (cell.className.indexOf("stuffing") == -1) return cell;
    
        // traverse Left
        while ((row>0) && (col>0) && (cell.className.indexOf("stuffing") >= 0)) {
            cell = table.rows[row].cells[--col];
        }
    
        // roll back one cell if no colSpan is found
        if (cell.colSpan == 1) cell = table.rows[row].cells[++col];
    
        // traverse Up
        while ((row>0) && (col>0) && (cell.className.indexOf("stuffing") >= 0)) {
            cell = table.rows[--row].cells[col];
        }
    
        return cell;
    }
    

    Usage:

    var tb = document.querySelector("table");
    getCellLocation(getSmartCell(tb,3,2)); // {row: 2, cell: 1}
    

    ATTENTION I have just checked the code of getSmartCell and it returns wrong result if there are two neighbouring rowspans. I need to fix this.

    Here is an example https://jsfiddle.net/goua3m13/

提交回复
热议问题