Finding column index using jQuery when table contains column-spanning cells

后端 未结 5 1359
日久生厌
日久生厌 2020-12-01 12:08

Using jQuery, how can I find the column index of an arbitrary table cell in the example table below, such that cells spanning multiple columns have multiple indexes?

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 12:56

    Here's a plugin which can calculate the 'noncolspan' index.

    $(document).ready(
            function()
            {
            console.log($('#example2').getNonColSpanIndex()); //logs 4
            console.log($('#example1').getNonColSpanIndex()); //logs 2
        }
    
    );
    
    $.fn.getNonColSpanIndex = function() {
        if(! $(this).is('td') && ! $(this).is('th'))
            return -1;
    
        var allCells = this.parent('tr').children();
        var normalIndex = allCells.index(this);
        var nonColSpanIndex = 0;
    
        allCells.each(
            function(i, item)
            {
                if(i == normalIndex)
                    return false;
    
                var colspan = $(this).attr('colspan');
                colspan = colspan ? parseInt(colspan) : 1;
                nonColSpanIndex += colspan;
            }
        );
    
        return nonColSpanIndex;
    };
    

提交回复
热议问题