【问题标题】:How to highlight table column based on th text using jquery?如何使用jquery根据文本突出显示表格列?
【发布时间】:2019-09-02 23:05:51
【问题描述】:

假设我有下表:

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

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

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

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

http://jsfiddle.net/8XSLF/

【问题讨论】:

  • 没有特定的类,我想它不能“面向未来”
  • 列名保证不变

标签: javascript jquery html jquery-selectors


【解决方案1】:

你需要得到th的索引有Highlight文本。所以使用: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>

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • GrafiCode 不是包含Highlighttbodytd
    • 我喜欢这个解决方案,但它需要获取标题索引并将其用作td:nth-child 选择器。
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-31
      • 2011-01-23
      • 1970-01-01
      • 2011-12-01
      • 2011-11-22
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      相关资源
      最近更新 更多