2

我有这样的表:

<table> 
<thead>
   <th>id </th><th>name </th><th>number </th><th>result </th> 
</thead>        
<tbody>
<tr>
 <td>stuff</td>
 <td>stuff</td>
 <td>stuff</td>
 <td>stuff</td> 
</tr>
</tbody>
 </table>

我想将class = "red"唯一添加到td标题为result

所以只有在页面加载时动态地使用 jquery 的结果列。

4

3 回答 3

2

.index()您可以使用然后使用:nth-child选择器应用类来获取标题的索引。

jsFiddle

在此处输入图像描述

var resultHeaderIndex = $('th:contains("result")').index();
$('td:nth-child(' + (resultHeaderIndex + 1) + ')').addClass('red')

如果您还想将类添加到标题中,那么您可以在获取索引之前简单地添加它:

jsFiddle

在此处输入图像描述

var resultHeaderIndex = $('th:contains("result")')
    .addClass('red')
    .index();
$('td:nth-child(' + (resultHeaderIndex + 1) + ')').addClass('red')
于 2013-03-27T03:32:53.543 回答
1

我认为使用 jQuery .index().eq()你可以很容易地做到这一点:

(function($){
    $.fn.colorColumn = function(headerText, color){
        var index = this.find("th").filter(function(){
            return ($(this).text() == headerText);
        }).css("backgroundColor", color).index();
        this.find("tr").each(function(){
            $(this).children().eq(index).css({backgroundColor: color});
        })
    }
})(jQuery);

$("table").colorColumn("number", "red");

工作演示:http: //jsfiddle.net/pitaj/eG5KE/

于 2013-03-27T03:43:04.510 回答
0

我会这样做的方式是使用条件和 jQuery each

$("th").each(function() {
    if ($(this).text() === "result") { $(this).addClass('red') }
}
于 2013-03-27T03:34:17.133 回答