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

2024-04-14

假设我有以下 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');
}

关于可能出什么问题的任何想法吗?

UPDATE:

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

LOOP:

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')意思是:找到我全部thead其中有tr班级。显然不是你想做的。

这里有一个应该可以工作的代码:

$('tbody tr td').each(function(index){
    //index contains the current td index in the parent tr (1,2,3),(1,2,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 不会执行任何操作。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JQuery:如果表头 有类,则将类添加到表单元格 的相关文章

随机推荐