Javascript 如何仅基于标题行应用一些jquery内容
我的桌子是这样的:Javascript 如何仅基于标题行应用一些jquery内容,javascript,jquery,html-table,jquery-selectors,Javascript,Jquery,Html Table,Jquery Selectors,我的桌子是这样的: <table> <thead> <th>id </th><th>name </th><th>number </th><th>result </th> </thead> <tbody> <tr> <td>stuff</td> <td>stuff</td&
<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>
id名称编号结果
东西
东西
东西
东西
我只想将class=“red”
添加到头为result
因此,当页面加载时,只有使用jquery动态生成结果列。您可以使用获取标题索引,然后使用应用类
如果还想将类添加到标题中,则可以在获取索引之前简单地添加它:
我的方法是使用条件查询和jQuery
每个
$("th").each(function() {
if ($(this).text() === "result") { $(this).addClass('red') }
}
我认为使用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");
工作演示:这提醒了我!更简单的方法:$('th:contains(“result”))。addClass('red')
这不会给整个列上色,只会给下面的单元格上色。将标题颜色设置为well@PitaJ该问题表示“我只想将class=“red”添加到那些标题为result的td中”好的,我想他是指包含标题,尽管短代码为+1。皮塔伊的反对意见很容易通过……=$('th:contains(“result”)).addClass('red').index();我将成为Stackoverflow上的一个混蛋,询问您为什么要这样做:这个表是静态的,还是从数据源加载的?如果它是从数据源加载的,那么您提到的类实际上应该在模板中;如果你不使用模板,你应该使用一个允许你使用模板的系统,比如angularjs.org。如果是静态的,这里的答案是正确的。对于添加/删除列而不是对其着色:我查看了您的网站pitaz,它在数据库连接中给出了错误:)
$("th").each(function() {
if ($(this).text() === "result") { $(this).addClass('red') }
}
(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");