我正在尝试将类分配给表标题。我正在尝试读取 td 的类名并将其分配给相关的 header 。任何帮助,将不胜感激。
<table >
<tr>
<th>hdrcol1</th>
<th>hdrcol2</th>
<th>hdrcol3</th>
</tr>
<tr>
<td class="title">col1</td>
<td class="desc">col2</td>
<td class="addclr">col3</td>
</tr>
<tr>
<td class="title">col11</td>
<td class="desc">col22</td>
<td class="addclr">co33</td>
</tr>
</table>
$('table tbody tr td').each(function(index){
if($('tr th').eq(index).attr('class') != ''){
//put this class on the current td
$(this).addClass($('thead tr th').eq(index).attr('class'));
}
});
最佳答案
您的选择器中有 thead
,但表格中没有 thead
。而且你的选择器也向后。正如您上面提到的,您希望将 tr
类添加到 th
中,而不是反之亦然(尽管您的评论似乎与您上面写的内容相矛盾)。
$('tr th').each(function(index){
if($('tr td').eq(index).attr('class') != ''){
// get the class of the td
var tdClass = $('tr td').eq(index).attr('class');
// add it to this th
$(this).addClass(tdClass );
}
});
关于Jquery为表中的th分配类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20864257/