Jquery为表中的th分配类

标签 jquery html-table

我正在尝试将类分配给表标题。我正在尝试读取 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'));
    }
});

What I tried in fiddle id here

最佳答案

您的选择器中有 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 );
    }
});

Fiddle

关于Jquery为表中的th分配类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20864257/

相关文章:

jquery - 随机背景 fadeIn() 到当前背景

javascript - 添加新元素后不触发事件

javascript - 为什么传递数据对象时第一个 $.ajax 会出错?

css - 无法在 Chrome DevTools 样式面板中更改 tr 元素的背景颜色

html - 如何纠正意外的 "table overflow"?

html - 自定义 TableRow 列宽

javascript - 单击 anchor 时如何设置/存储 cookie

javascript - JQuery/JavaScript - 从单词列表创建表格

javascript - 如何在不添加到第一个表的情况下将表行专门添加到第二个表

html - 如何使一个表格行扩展到表格其余部分的宽度之外?