简体   繁体   English

表cellIndex和rowIndex与colspan / rowspan

[英]Table cellIndex and rowIndex with colspan/rowspan

I was using the answer provided in: 我正在使用以下提供的答案:

How can I find each table cell's "visual location" using jQuery? 如何使用jQuery找到每个表格单元格的“可视位置”?

But it doesn't seem to work in this case: http://jsfiddle.net/TRr6C/9/ 但它似乎在这种情况下不起作用: http//jsfiddle.net/TRr6C/9/

Notice the 1,3 1,4 and 2,4 should be 1,4 1,5 and 2,5 请注意,1,3 1,4和2,4应为1,4 1,5和2,5

Anyone see whats wrong? 有人看到什么错了吗?

Or is there any better solution to get the cellIndex and rowIndex from a table cell taking into consideration colspan and rowspan? 或者有没有更好的解决方案从表格单元格中获取cellIndex和rowIndex考虑colspan和rowspan?

Here is the code: 这是代码:

function getCellLocation(cell) {

    var cols = cell.closest("tr").children("td").index(cell);
    var rows = cell.closest("tbody").children("tr").index(cell.closest("tr"));
    var coltemp = cols;
    var rowtemp = rows;

    cell.prevAll("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("tbody").children("tr").index($(this));
        // assign the row to a variable for later use
        var row = $(this);
        row.children("td").each(function() {
            // fetch all cells of this row
            var colindex = row.children("td").index($(this));
            //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 (colspn && rowspn) {
                    if(rowindex + rowspn > rows)
                    cols += colspn;                    
                }
            }

        });
    });

    return {
        rows: rows,
        cols: cols
    };
}

My solution is in form of jQuery plugin since I can imagine more than one purpose of having this information. 我的解决方案是jQuery插件的形式,因为我可以想象有这个信息的不止一个目的。 It can be used as in: 它可以用作:

$("table tbody td").each(function(){ 
    $(this).text( $(this).cellPos().top +","+ $(this).cellPos().left );
});

The position is in form of { top: rows, left: cols } . 该位置采用{ top: rows, left: cols } On its first call, table is scanned and TD elements get data items with their cached position. 在第一次调用时,扫描表格, TD元素获取具有缓存位置的data项。 (Cache can be rebuilt by calling with argument true ). (可以通过使用参数true调用来重建缓存)。 All further calls just return that cached value. 所有进一步的调用只返回缓存的值。

Hope this helps! 希望这可以帮助!

jsfiddle 的jsfiddle

Full source: 完整来源:

/*  cellPos jQuery plugin
    ---------------------
    Get visual position of cell in HTML table (or its block like thead).
    Return value is object with "top" and "left" properties set to row and column index of top-left cell corner.
    Example of use:
        $("#myTable tbody td").each(function(){ 
            $(this).text( $(this).cellPos().top +", "+ $(this).cellPos().left );
        });
*/
(function($){
    /* scan individual table and set "cellPos" data in the form { left: x-coord, top: y-coord } */
    function scanTable( $table ) {
        var m = [];
        $table.children( "tr" ).each( function( y, row ) {
            $( row ).children( "td, th" ).each( function( x, cell ) {
                var $cell = $( cell ),
                    cspan = $cell.attr( "colspan" ) | 0,
                    rspan = $cell.attr( "rowspan" ) | 0,
                    tx, ty;
                cspan = cspan ? cspan : 1;
                rspan = rspan ? rspan : 1;
                for( ; m[y] && m[y][x]; ++x );  //skip already occupied cells in current row
                for( tx = x; tx < x + cspan; ++tx ) {  //mark matrix elements occupied by current cell with true
                    for( ty = y; ty < y + rspan; ++ty ) {
                        if( !m[ty] ) {  //fill missing rows
                            m[ty] = [];
                        }
                        m[ty][tx] = true;
                    }
                }
                var pos = { top: y, left: x };
                $cell.data( "cellPos", pos );
            } );
        } );
    };

    /* plugin */
    $.fn.cellPos = function( rescan ) {
        var $cell = this.first(),
            pos = $cell.data( "cellPos" );
        if( !pos || rescan ) {
            var $table = $cell.closest( "table, thead, tbody, tfoot" );
            scanTable( $table );
        }
        pos = $cell.data( "cellPos" );
        return pos;
    }
})(jQuery);

vanilla js version of @nrodic 's scanTable() @nrodic的scanTable()的香草js版本

function scanTable(table)
{
    var m = [];
    for(var y=0; y<table.rows.length; y++)
    {
        var row = table.rows[y];

        for(var x=0;x<row.cells.length;x++)
        {
            var cell = row.cells[x], xx = x, tx, ty;

            for(; m[y] && m[y][xx]; ++xx);                        // skip already occupied cells in current row

            for(tx = xx; tx < xx + cell.colSpan; ++tx)            // mark matrix elements occupied by current cell with true
            {
                for(ty = y; ty < y + cell.rowSpan; ++ty)
                {
                    if( !m[ty] ) m[ty] = [];                    // fill missing rows
                    m[ty][tx] = true;
                }
            }

            // do here whatever you want with
            // xx: the horizontal offset of the cell
            // y: the vertical offset of the cell

        }
    }
};

I have improved user652649's answer so that function returns cell according to given coordinates and does not miss cells with col/rowspan, here is the gist , or just a code: 我已经改进了user652649的答案,以便函数根据给定的坐标返回单元格,并且不会错过具有col / rowspan的单元格, 这里是要点 ,或者只是代码:

/**
 * Returns the cell of the table by given (x;y) coordinates considering colSpan and rowSpan of the cells.
 * @param {HTMLElement} table - HTML table
 * @param {number} x - X position in table matrix
 * @param {number} y - Y position in table matrix
 * @returns {HTMLElement|null}
 */
var getTableCell = function (table, x, y) {
    var m = [], row, cell, xx, tx, ty, xxx, yyy;
    for(yyy = 0; yyy < table.rows.length; yyy++) {
        row = table.rows[yyy];
        for(xxx = 0; xxx < row.cells.length; xxx++) {
            cell = row.cells[xxx];
            xx = xxx;
            for(; m[yyy] && m[yyy][xx]; ++xx) {}
            for(tx = xx; tx < xx + cell.colSpan; ++tx) {
                for(ty = yyy; ty < yyy + cell.rowSpan; ++ty) {
                    if (!m[ty])
                        m[ty] = [];
                    m[ty][tx] = true;
                }
            }
            if (xx <= x && x < xx + cell.colSpan && yyy <= y && y < yyy + cell.rowSpan)
                return cell;
        }
    }
    return null;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM