代码之家  ›  专栏  ›  技术社区  ›  woggles

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

  •  1
  • woggles  · 技术社区  · 7 年前

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

    2 回复  |  直到 7 年前
        1
  •  2
  •   Mohammad DefenestrationDay    7 年前

    你需要得到 th 突出 文本。所以使用 :contains() 选择它,然后使用 .index() td

    请注意 :包含() Highlighted Text 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
  •  0
  •   GrafiCode    7 年前

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

    $( "body > table > tbody > tr > td:contains('Highlight')" ).css('background-color', 'pink');
    
        3
  •  0
  •   woggles    7 年前

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

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