如何使用jQuery突出显示基于文本的表列?

时间:2019-04-12 08:16:45

标签: javascript jquery html jquery-selectors

说我有下表:

<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>

,我想突出显示所有突出显示列。如何根据标题文本执行此操作?

我意识到可以通过选择第n个孩子来实现,但是将来该如何针对可能的列顺序更改进行证明。

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

http://jsfiddle.net/8XSLF/

3 个答案:

答案 0 :(得分:2)

您需要获取具有{strong>突出显示文本的th索引。因此,使用:contains()选择器选择它,然后使用.index()查找它的索引。最后,选择每个thtd的索引等于找到的索引。

请注意,:contains()选择器select元素还具有不需要的文本,例如HighlightedText Highlighted。如果您的表格文字不是恒定的,请改用.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>

答案 1 :(得分:0)

由于您指定的列名不会更改,因此可以使用jQuery.contains:

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

答案 2 :(得分:0)

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

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