在两个表中添加jQuery悬停效果

Jam*_*mes 2 css jquery html-table jquery-selectors

我有两个div彼此相邻的HTML表.第二个div可以在水平方向上滚动,所以实际上它看起来像一个大表,其中前几列被"冻结"而其他列可以滚动.

当用户将鼠标悬停在一个表中时,以下jQuery可以很好地突出显示一行:

$("table.grid tr:not(:first-child)")
  .hover(
    function () { $(this).addClass("highlight"); },
    function () { $(this).removeClass("highlight"); }
  );
Run Code Online (Sandbox Code Playgroud)

请注意,:not(:first-child)可以防止标题突出显示.

我如何修改它,以便它突出显示另一个表中的相应行(也有一个类grid)?

换句话说,如果我将鼠标悬停n在任一表中的n第th行上,则会突出显示两个表中的第th行.

编辑:HTML看起来像:

<div>
  <div style="float: left">
    <table id="names" class="grid">
      <tr><th>Last</th><th>First</th></tr>
      <tr><td>Smith</td><td>John</td></tr>
      <!-- etc -->
      </table>
  </div>
  <div style="float: left; overflow-x: scroll">
    <table id="results" class="grid">
      <tr><th>Test 1</th><th>Test 2</th></tr>
      <tr><td>50%</td><td>70%</td></tr>
      <!-- etc -->
    </table>
  </div>
  <div style="clear: both">
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 8

关键是要抓住所有的<tr>开头秒,然后结合起来$(this).index(),filter:nth-child一次选择两个表中的行权:

var $trs = $('table.grid tr:not(:first-child)');
$trs.hover(
    function() {
        var i = $(this).index() + 1;
        $trs.filter(':nth-child(' + i + ')').addClass('highlight');
    },
    function() {
        var i = $(this).index() + 1;
        $trs.filter(':nth-child(' + i + ')').removeClass('highlight');
    }
);
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/ambiguous/54thG/

index调用为您<tr>提供了相对于其兄弟姐妹的位置$trs,然后您调整为1,因为它index是从零开始的,但是:nth-child(作为CSS选择器)是基于一的,并且同时在两行上调整类.