jquery按标题值突出显示表列

时间:2015-04-16 13:31:27

标签: jquery

如何根据<th>Mar</th>值突出显示表格列?如果头部包含例如Mar,那么使用标题突出显示整列?

&#13;
&#13;
var target = $("table th:contains('Mar')").css("background-color", "#FF0000");

$('table tr td:nth-child(' + (target.index() + 1) + ')').css("background-color", "#FF0000");


  
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


        

<table>
  <thead>
    <tr>
      <th>Jan</th>
      <th>Feb</th>
      <th>Mar</th>
      <th>Apr</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Val</td>
      <td>Val</td>
      <td>Val</td>
      <td>Val</td>
    </tr>
    <tr>
      <td>Val</td>
      <td>Val</td>
      <td>Val</td>
      <td>Val</td>      
    </tr>
    <tr>
      <td>Val</td>
      <td>Val</td>
      <td>Val</td>
      <td>Val</td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
 $(document).ready(function(){
 var index = $('th:contains("Mar")').eq(0).index();
 $("tr").each(function(rowIndex, row){
    $(row).find("th:eq(" + index + ")").css('background', 'green');
    $(row).find("td:eq(" + index + ")").css('background', 'green');
 });
});
</script>
<table>
  <thead>
    <tr>
      <th>Jan</th>
      <th>Feb</th>
      <th>Mar</th>
      <th>Apr</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Val</td>
      <td>Val</td>
      <td>Val</td>
      <td>Val</td>
    </tr>
    <tr>
      <td>Val</td>
      <td>Val</td>
      <td>Val</td>
      <td>Val</td>      
    </tr>
    <tr>
      <td>Val</td>
      <td>Val</td>
      <td>Val</td>
      <td>Val</td>
    </tr>
  </tbody>
</table>

答案 1 :(得分:-1)

您可以使用列组标记列,如下所示:

<table>
    <colgroup>
        <col>
        <col>
        <col>
    </colgroup>
....
</table>

然后,在通过查询<th>元素找到所需列的索引后,设置匹配的<col>元素的样式。这比遍历表的所有行更有效。