如何使用 jquery 根据文本突出显示 table 列?

How to highlight table column based on th text using jquery?

假设我有以下 table:

<table width=200 border=1>
  <tr>
    <th>Ignore</th>
    <th>Highlight</th>
    <th>Ignore</th>
  </tr>
  <tr>
    <td>yep</td>
    <td>yep</td>
    <td>yep</td>
  </tr>
  <tr>
      <td>yep</td>
      <td>yep</td>
      <td>yep</td>
  </tr>
</table>

并且我想突出显示所有 突出显示 列。我如何根据 header 文本执行此操作?

我意识到它可以通过选择第 n 个 child 来实现,但是未来如何证明它可以防止可能的列顺序更改。

$('body > table > tbody > tr > td:nth-child(2)').css('background-color', 'pink');

http://jsfiddle.net/8XSLF/

您需要获取 th 的索引具有 Highlight 文本。所以使用 :contains() selector to selecting it and then use .index() 来查找它的索引。最后,select 每个 thtd 的索引等于找到的索引。

请注意,:contains() select 或 select 元素也包含不需要的文本,例如 HighlightedText Highlighted。如果您的 table 文本不固定,请改用 .filter()

var i = $("table th:contains('Highlight')").index();
$("table tr th, table tr td").filter(function(){
  return $(this).index() == i;
}).css("background", "pink");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table width=200 border=1>
<tr>
    <th>Ignore</th>
    <th>Highlight</th>
    <th>Ignore</th>
</tr>
<tr>
    <td>yep</td>
    <td>yep</td>
    <td>yep</td>
</tr>
 <tr>
    <td>yep</td>
    <td>yep</td>
    <td>yep</td>
</tr>
</table>

因为你指定的列名不会改变,你可以使用jQuery.contains:

$( "body > table > tbody > tr > td:contains('Highlight')" ).css('background-color', 'pink');

需要在多个表中突出显示:最终解决方案

$("th:contains('Highlight')").each(function() {
    $(this).closest('table').find('td:nth-child(' + ($(this).index() + 1) +')').css('background-color', 'pink');
});