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

后端 未结 5 785
小蘑菇
小蘑菇 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:37

    Since the accepted answer is missing a return statement and only works with tbody and td (and not with thead and th) I did some slight adjustments to make it work:

    function getCellLocation(cell) {
    
        var cols = cell.closest("tr").children("th, td").index(cell);
        var rows = cell.closest("thead, tbody").children("tr").index(cell.closest("tr"));
    
        cell.prevAll("th, td").each(function() {
            cols += ($(this).attr("colspan")) ? parseInt($(this).attr("colspan")) - 1 : 0;
        });
    
        cell.parent("tr").prevAll("tr").each(function() {
            //get row index for search cells
            var rowindex = cell.closest("thead, tbody").children("tr").index($(this));
            // assign the row to a variable for later use
            var row = $(this);
            row.children("th, td").each(function() {
                //check if this cell comes before our cell
                if (cell.offset().left > $(this).offset().left) {
                    // check if it has both rowspan and colspan, because the single ones are handled before
                    var colspn = parseInt($(this).attr("colspan"));
                    var rowspn = parseInt($(this).attr("rowspan"));
                    if (rowspn && rowindex + rowspn > rows) {
                        cols += colspn ? colspn : 1;
                    }
                }
    
            });
        });
        return cols;
    }
    

提交回复
热议问题