我想给表格行一个单元格的类,如下所示:
我有这张桌子,
<table id="mytable">
<tr>
<th>Name</th>
<th>Favorite color</th>
</tr>
<td>James</td>
<td>red</td>
</tr>
<tr>
<td>John</td>
<td>blue</td>
</tr>
</table>
我想让它最终像这样。
<table id="mytable">
<tr>
<th>Name</th>
<th>Favorite color</th>
</tr>
<tr class="red">
<td>James</td>
<td>red</td>
</tr>
<tr class="blue">
<td>John</td>
<td>blue</td>
</tr>
</table>
这可能吗?
答案 0 :(得分:4)
您可以使用addClass
方法:
$('tbody tr').addClass(function(){
return $('td:last', this).text()
})
请注意,您在tr
之前缺少打开<td>James</td>
标记。
答案 1 :(得分:0)
使用您的HTML:
$("tr:not(:first)").each(function(i) {
$(this).addClass($(this).children("td").last().text());
});
这是做什么的:
tr
开始:not
的参数,在这种情况下告诉我们我们不希望整个元素选择中的第一个元素callback
函数的开头。 i
表示每个元素在通过td
,因此我们使用子选择器来抓住那些孩子