jQuery选择带有rowspan的表中的可视列

Adm*_*eck 8 jquery html-table jquery-selectors

我已经看到了一些类似的问题但没有解决这个具体问题.请考虑下表:

<table id="foo" border="1px">
    <tr>
        <td rowspan="2">one</td>
        <td>two</td>
        <td rowspan="2">three</td>
        <td>four</td>
        <td>five</td>
    </tr>
    <tr>
        <td rowspan="2">two</td>
        <td>four</td>
        <td>five</td>
    </tr>
    <tr>
        <td rowspan="2">one</td>
        <td>three</td>
        <td>four</td>
        <td>five</td>
    </tr>
    <tr>
        <td>two</td>
        <td>three</td>
        <td>four</td>
        <td>five</td>
    </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

使用jQuery,如何选择特定视觉列中的所有项目?例如,如果我想选择第3列,我应该将所有td与'3'作为内容.

utt*_*t73 6

这个插件处理复杂的colspan和rowspan选择:

$('#foo th:nth-col(3), #foo td:nth-col(3)').css("color","red");
Run Code Online (Sandbox Code Playgroud)

  • 由于伪选择器API的更改而无法在jQuery 1.8+上运行 - http://stackoverflow.com/questions/11624345/getting-the-match-object-in-a-custom-filter-selector-in -jquery-1-8 (2认同)

Jam*_*gne 5

没有看过发布的插件,但我发现这个问题很有趣,所以我创造了一个小提琴!

http://jsfiddle.net/PBPSp/

如果插件工作它可能比这更好,但这是一个有趣的练习所以我也可以发布它.

更改colToGet为要突出显示的列.

$(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);
                }
            }
        });
    });
});?
Run Code Online (Sandbox Code Playgroud)