Jquery将类分配给表中的th

Jquery将类分配给表中的th,jquery,html-table,Jquery,Html Table,我正在尝试将类分配给表标题。我试图读取td的类名,并将其分配给相关的th头。任何帮助都将不胜感激 <table > <tr> <th>hdrcol1</th> <th>hdrcol2</th> <th>hdrcol3</th> </tr> <tr> <td class="title">col1</td> &

我正在尝试将类分配给表标题。我试图读取td的类名,并将其分配给相关的th头。任何帮助都将不胜感激

<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'));
    }
});

hdrcol1
hdrcol2
hdrcol3
可乐
可乐
可乐
col11
col22
二氧化碳33
$('table tbody tr td')。每个(函数(索引){
如果($('tr th').eq(index).attr('class')!=“”){
//将该类设置为当前td
$(this.addClass($('thead tr th').eq(index.attr('class')));
}
});

选择器中有
thead
,但表中没有
thead
。你也有你的选择器向后。如上所述,您希望将
tr
类添加到
th
,而不是相反(尽管您的评论似乎与您上面所写的内容相矛盾)


选择器中有
thead
,但表中没有
thead
。你也有你的选择器向后。如上所述,您希望将
tr
类添加到
th
,而不是相反(尽管您的评论似乎与您上面所写的内容相矛盾)


您的表是否总是以这种方式格式化?不,这是我举的常见示例,但tds将具有类似的类。您的表是否总是以这种方式格式化?不,这是我举的常见示例,但tds将具有类似的类。
$('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 );
    }
});
$("tr th").each(function(i) {
    var tdClass = $("tr td").eq(i).attr("class");
    if (tdClass != "") $("tr th").eq(i).addClass(tdClass);
});