javascript – JQuery:如果表头有一个类,则将类添加到表单元格

前端之家收集整理的这篇文章主要介绍了javascript – JQuery:如果表头有一个类,则将类添加到表单元格前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我有以下html:

<table>
    <thead>
        <tr>
            <th class="alignRight">Header1</th>
            <th>Header2</th>
            <th class="alignLeft">Header3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Row1</td> //Add class="alignRight"
            <td>Row1</td>
            <td>Row1</td> //Add class="alignLeft"
        </tr>
        <tr>
            <td>Row2</td> //Add class="alignRight"
            <td>Row2</td>
            <td>Row2</td> //Add class="alignLeft"
        </tr>
        <tr>
            <td>Row3</td> //Add class="alignRight"
            <td>Row3</td>
            <td>Row3</td> //Add class="alignLeft"
        </tr>
    </tbody>
</table>

如果THEAD中的TR包含类“alignRight”或“alignLeft”,我想将相同的类应用于TBODY中的相应TD.

我正在使用JQuery并尝试了以下方法,但它们似乎都没有正常工作:

$('tr').has('th.alignRight').addClass('th.alignRight');
$('tr').has('th.alignLeft').addClass('th.alignLeft');

$('thead.tr').has('th.alignRight').addClass('tbody.th.alignRight');
$('thead.tr').has('th.alignLeft').addClass('tbody.th.alignLeft');

if ($('thead.tr').has('th.alignRight')){
    $('tbody.tr').addClass('th.alignRight');
}

if ($('thead.tr').has('th.alignRight')){
    $('tbody.tr.td').addClass('alignRight');
}

关于什么可能出错的任何想法?

更新:

我想补充一点,我已经使用.each()循环遍历表.我只需要添加条件,如果当前表头具有该类,则将该相同的类添加到表格单元格中.在当前迭代期间添加额外的迭代听起来会导致性能问题.真的吗?

环:

function(res) {
    var tbl_body = "";
    $.each(res,function () {
        var tbl_row = "";
        $.each(this,function (k,v) {

          //Irrelevant code

            tbl_row += "<td>" + v + "</td>";
        })
        tbl_body += "<tr>" + tbl_row + "</tr>";
    })
    $("#print").html(tbl_body);
    },//Other irrelevant code

解决方法

我认为你没有看到jquery选择器是如何工作的.
$(‘thead.tr’)表示:找到我所有拥有tr类的thead.显然不是你想做的.

这里应该有一个代码

$('tbody tr td').each(function(index){
    //index contains the current td index in the parent tr (1,2,3),(1,3)...
    //if the corresponding th has a class
    if($('thead tr th').eq(index).attr('class') != ''){
        //put this class on the current td
        $(this).addClass($('thead tr th').eq(index).attr('class'));
    }
});

检查td是否有类是没有必要的,因为如果给它一个空参数,addClass什么也不做.

猜你在找的jQuery相关文章