首页 > 解决方案 > 跳转到表格行并在 html 中突出显示它?

问题描述

我有一个长表,不同的条目相互关联,所以我将它们链接成这样:

<tr>
    <th>Thing </th>
    <th>related to Thing </th>
</tr>
<tr>
    <td><a name = "t1"/>Thing 1</td>
    <td><a href = "#t2">Thing2 is related </a></td>
</tr>
<tr>
    <td><a name = "t2"/>Thing2</td>
    <td><a href = "#t1">Thing1 is related </a></td>
</tr>

现在,我希望当我单击“Thing2 相关”时,我会跳下页面(哪个有效),但我希望该行很快亮起以指出哪一行是指。有什么办法吗?

标签: htmlhtml-tablerowhighlight

解决方案


如果可以接受一点 jQuery,那么可以。您将不得不对您的 html 做一个小改动,将name属性更改为id.

// Listen for clicks on '.link' elements
$('table').on('click', '.link', function() {
  // Find previously selected items and remove the class, restricting the search to the table.
  $('.related', 'table').removeClass('related')
  // Find the click target
  target = $(this).attr('href');
  // Find its 'tr' and highlight it
  $(target).closest('tr').addClass('related')
});
.related {
  background-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <th>Thing </th>
    <th>related to Thing </th>
  </tr>
  <tr>
    <td><a id="t1" />Thing 1</td>
    <td><a class="link" href="#t2">Thing2 is related </a></td>
  </tr>
  <tr>
    <td><a id="t2" />Thing2</td>
    <td><a class="link" href="#t1">Thing1 is related </a></td>
  </tr>
</table>


推荐阅读