jQuery:垂直获取下一个表格单元格

jQuery: Get next table cell vertically

本文关键字:表格 单元格 下一个 获取 垂直 jQuery      更新时间:2023-09-26

如何使用jQuery访问传统网格布局html table中给定单元格下方的单元格(td)?

我知道以下内容会将nextCell设置为单击单元格右侧的单元格,因为它们是直系兄弟,但我正在尝试检索单击单元格下方的单元格:

$('td').click(function () {
    var nextCell = $(this).next('td');
});

我最好不使用类或id。

试试这个:

$("td").click(function(){
  // cache $(this);
  var $this = $(this);
  // First, get the index of the td.
  var cellIndex = $this.index();
  // next, get the cell in the next row that has
  // the same index.
  $this.closest('tr').next().children().eq(cellIndex).doSomething();
});
$('td').click(function () {
  var index = $(this).prevAll().length
  var cellBelow = $(this).parent().next('tr').children('td:nth-child(' + (index + 1) + ')')
});

index是当前行中单元格的基于0的索引(prevAll查找该单元格之前的所有单元格)。

然后在下一行中,我们在索引+1处找到nth-child td(nth-child从1开始,因此是+ 1)。

怎么样:

$('td').click(function () {
    var nextCell = $(this).parent().next().find("td:nth-child(whatever)");
});

如果你想在不使用选择器的情况下完成,你可以执行:

    function getNextCellVertically(htmlCell){
        //find position of this cell..
        var $row = $(htmlCell).parent();
        var cellIndex = $.inArray(htmlCell, $row[0].cells);
        var table = $row.parent()[0];
        var rowIndex = $.inArray($row[0], table.rows);
        //get the next cell vertically..
        return (rowIndex < table.rows.length-1) ? 
                table.rows[rowIndex+1].cells[cellIndex] : undefined;
    }
    $('td').click(function () {
        var nextCell = getNextCellVertically(htmlCell);
        //...
    });

效率在这里并不重要,但这样做会更快——在超过100000次迭代的测试中,它比基于选择器的方法快2-5倍。

每个表行中的单元格数量是否相等?如果是,您可以获得有问题单元格的"计数",然后在next('tr')中选择相应的单元格。