jquery select 第 n 个 children 第 n 个 children

jquery select nth children of a nth children

我有一个 table,我想在悬停一个单元格时突出显示该单元格和类似的单元格,也就是说,如果我将鼠标放在单元格 (3,1) 中,它会突出显示该单元格和 (1,3)。我有这个代码:

$('td').on('mouseover mouseout', function(){
             $(this)
             .add($(this).parent().parent()
             .children()[$(this).index()]).toggleClass('hover');
      });

这样我可以 select 正确的行,但我只需要 select 该行中的正确单元格,即模拟单元格。我试过一些 select 或我无法导航到那个单元格。

这里是an example

试试这个:

当您将鼠标悬停在 (x,y) 单元格上时,(y,x) 单元格也会获得 'hover' class

勾选DEMO

$('td').on('mouseover', function(){
    var that = $(this);
    that.addClass('hover');
    var x = that.index();
    var y = that.closest('tr').index();
    $('table').find('tr').eq(x).find('td').eq(y).addClass('hover');
}).on('mouseout', function() {
    $('td').removeClass('hover');
})
$('td').on('mouseover mouseout', function () {
    var i = this.cellIndex, 
        pi = this.parentNode.rowIndex,
        cell = this.parentNode.parentNode.rows[i].cells[pi];

    $(this).add(cell).toggleClass('hover');
});

https://jsfiddle.net/1u3w7b3q/2/

您可以使用 index()

$('td').on('mouseover mouseout', function () {
    $(this).toggleClass('hover');
    if ($(this).index() !== $(this).parent().index()) {
        $('tr:eq(' + $(this).index() + ') td:eq(' + $(this).parent().index() + ')').toggleClass('hover');
    }
});

Demo Fiddle

$('td').on('mouseover mouseout', function(){
                 $(this).toggleClass('hover');
                 $index = $(this).index()+1;
                 $index2 = $(this).parent().index()+1;
                 $index != $index2?$('tr:nth-child('+$index+') > td:nth-child('+$index2+')').toggleClass('hover'):'';
          });

jsfiddle: https://jsfiddle.net/aEwE4/106/