jquery选择第n个孩子的第n个孩子

时间:2015-04-14 09:14:12

标签: jquery jquery-selectors

我有一张桌子,当我悬停一个单元格时,它会突出显示那个单元格和simetric单元格,如果我将鼠标放在单元格(3,1)中,它会突出显示该单元格和(1,3)我有这段代码:

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

这样我可以选择正确的行,但我只需要选择该行中的正确单元格,即simetric单元格。我尝试过一些选择器,但我无法导航到那个单元格。

这是an example

4 个答案:

答案 0 :(得分:4)

试试这个:

当您将鼠标悬停在(x,y)单元格上时,(y,x)单元格也会获得“悬停”类

检查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');
})

答案 1 :(得分:3)

您可以使用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

答案 2 :(得分:2)

$('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/

答案 3 :(得分:0)

$('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/