当表包含列跨越单元格时,使用jQuery查找列索引

Bra*_*bby 22 javascript jquery html-table

使用jQuery,如何在下面的示例表中找到任意表单元格的列索引,以便跨越多列的单元格具有多个索引?

HTML

<table>
  <tbody>
    <tr>
      <td>One</td>
      <td>Two</td>
      <td id="example1">Three</td>
      <td>Four</td>
      <td>Five</td>
      <td>Six</td>
    </tr>
    <tr>
      <td colspan="2">One</td>
      <td colspan="2">Two</td>
      <td colspan="2" id="example2">Three</td>
    </tr>
    <tr>
      <td>One</td>
      <td>Two</td>
      <td>Three</td>
      <td>Four</td>
      <td>Five</td>
      <td>Six</td>
    </tr>
  </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

jQuery的

var cell = $("#example1");
var example1ColIndex = cell.parent("tr").children().index(cell);
// == 2. This is fine.

cell = $("#example2");
var example2ColumnIndex = cell.parent("tr").children().index(cell);
// == 2. It should be 4 (or 5, but I only need the lowest). How can I do this?
Run Code Online (Sandbox Code Playgroud)

Sol*_*ogi 29

这是一个可以计算'noncolspan'指数的插件.

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


pha*_*roh 5

我的解决方案与SolutionYogi非常相似,减去了插件的创建.它花了我一点时间......但我仍然为它感到骄傲所以这里是:)

cell = $("#example2");
var example2ColumnIndex2 = 0;

cell.parent("tr").children().each(function () {
    if(cell.get(0) != this){
        var colIncrementor = $(this).attr("colspan");
        colIncrementor = colIncrementor ? colIncrementor : 1;
        example2ColumnIndex2 += parseInt(colIncrementor);
    }
});
console.log(example2ColumnIndex2);
Run Code Online (Sandbox Code Playgroud)