jQuery select visual column in table with rowspan

前端 未结 5 1128
迷失自我
迷失自我 2021-01-02 11:58

I have seen a few similar questions but nothing that answers this specific problem. Consider the following table:

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-02 12:24

    Haven't looked at the posted plugin, but I found the question interesting so I created a fiddle!

    http://jsfiddle.net/PBPSp/

    If the pluggin works it may be better than this, but it was a fun exercise so I may as well post it.

    Change colToGet to whichever column you want to highlight.

    $(function() {
        var colToGet = 2;
    
        var offsets = [];
        var skips = [];
    
        function incrementOffset(index) {
            if (offsets[index]) {
                offsets[index]++;
            } else {
                offsets[index] = 1;
            }
        }
    
        function getOffset(index) {
            return offsets[index] || 0;
        }
    
        $("#foo > tbody > tr").each(function(rowIndex) {
    
            var thisOffset = getOffset(rowIndex);
    
            $(this).children().each(function(tdIndex) {
    
                var rowspan = $(this).attr("rowspan");
    
                if (tdIndex + thisOffset >= colToGet) {
                    if(skips[rowIndex]) return false;
    
                    $(this).css("background-color", "red");
    
                    if (rowspan > 1) {
                        for (var i = 1; i < rowspan; i++) {
                            skips[rowIndex + i] = true;
                        }
                    }
    
                    return false;
                }
    
                if (rowspan > 1) {
                    for (var i = 1; i < rowspan; i++) {
                        incrementOffset(rowIndex + i);
                    }
                }
            });
        });
    });​
    

提交回复
热议问题