在正文中计算tr,它们具有一定的风格特征

Count tr in tbody, which have a certain style trait

本文关键字:具有一 风格 特征 正文 计算 tr      更新时间:2023-11-09

我试图计算tbody中具有white background-colortd的数量。我需要在计数后更新span的文本。我的span的类是.attendenceCount

$(".attendenceCount").closest('tbody')...

HTML

<table>
    <thead>
        <tr>
            <th>Søløve 16:50-17:30 (3017) <span style="color:black;" class="attendenceCounter">tmp</span>
            </th>
        </tr>
    </thead>
    <tbody>
        <tr style='background-color:white;'>
            <td>Albert Hvistendahl Fabel</td>
        </tr>
        <tr style='background-color:green;'>
            <td>Albert Hvistendahl Fabel</td>
        </tr>
        <tr style='background-color:white;'>
            <td>Albert Hvistendahl Fabel</td>
        </tr>
        <tr style='background-color:green;'>
            <td>Alma Valbjørn Bratved</td>
        </tr>
        <tr style='background-color:white;'>
            <td>Albert Hvistendahl Fabel</td>
        </tr>
    </tbody>
</table>

这怎么可能呢?

现在您引用了HTML的新答案

现在您已经引用了HTML,您将其显示为:

<tr style='background-color:white;'>
    <td>Albert Hvistendahl Fabel</td>
</tr>

如果style属性将真的看起来完全像这样,那么有一个快捷方式:

var tds = $(".attendenceCount").closest('tbody').find('tr[style="background-color:white;"] td');

但是,如果您更改style属性(例如,在background-color:white之间添加一个空格),这将停止工作。

主要建议必须更改HTML,这样您就可以更容易地查找内容,比如类。


原始答案

没有捷径,你必须找到所有的td元素,并在它们之间循环,检查它们是否有白色的background-color(可能是通过filter)。注意element.style.backgroundColor(或$element.css("background-color"))可能是十六进制或rgb表示法,因此必须考虑到这一点

类似的东西

var whiteBackgroundTds =
    $(".attendenceCount").closest('tbody').find('td').filter(onlyWhiteBG);
function onlyWhiteBG() {
    var bgcolor = (this.style.backgroundColor || "").toLowerCase(),
        m,
        isWhite = false;
    if (bgcolor.substring(0, 3) === "rgb") {
        // Handle rgb or rgba (check this rex, it's off-the-cuff
        m = /'s*rgb(?:a)?'('s*('d+)'s*,'s*('d+)'s*,'s*('d+)/;
        if (m && m[1] === "255" && m[2] === "255" && m[3] === "255") {
            isWhite = true;
        }
    }
    else switch (bgcolor) {
        case "white": // Not likely
        case "#ffffff":
        case "#fff":
            isWhite = true;
    }
    return false; // Not white
}

但这几乎是伪代码。这个想法只是为你指明正确的方向。

请注意,这将仅与指定了background-colortd元素匹配。如果您需要找到通过样式指定的,请使用$(this).css("background-color")而不是上面的this.style.backgroundColor

下面是我在jsfiddle上做的一个例子。它使用rgb作为颜色,因为我使用铬,你可能需要改变它(看看T.J.Crowder关于这一点的回答)。

function calc_attendence() {
    var count = 0,
        tds = $('tbody td');
    $.each(tds, function (index, value) {
        var color = $(value).css('background-color');
        if (color == 'rgb(255, 255, 255)') { //works for me because I'm using chrome
            count = count + 1
        }
    });
    return count
};
相关文章: