You need to enable JavaScript to run this app. 如何在PHP循环中用if条件按到期日动态绑定HTML表格行CSS类
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP循环中用if条件按到期日动态绑定HTML表格行CSS类

可直接落地的实现方案

第一步:先修正原状态判断的逻辑顺序漏洞

原判断逻辑存在顺序bug:如果先判断$expire <=30,那么所有已经过期($expire <=0)的站点会直接命中第一个分支,永远不会进入expired的判断分支。正确的判断优先级应该是:先判断是否已经过期,再判断是否临近到期,最后判定为正常状态。
修正后的状态判断逻辑:

// 循环内计算完$expire后执行
if ($expire <= 0) {
    $row_class = 'expired';
} elseif ($expire <= 30) {
    $row_class = 'expiring';
} else {
    $row_class = 'active';
}

第二步:将类名绑定到表格行(<tr>标签)上

只需要在循环渲染<tr>标签的时候,把计算好的$row_class拼到标签的class属性上即可,不需要单独echo类名,直接整合进原有渲染结构就行。

完整整合后的页面代码

<div class="col-lg table-responsive">
    <table class="table table-hover">
        <thead class="thead thead-dark">
        <tr>
            <th scope="col">#</th>
            <th scope="col">title</th>
            <th scope="col">date</th>
            <th scope="col">contact person</th>
            <th scope="col">phone</th>
            <th scope="col">status</th>
            <th scope="col" >action</th>
        </tr>
        </thead>
        <tbody>
        <?php
        $button_upd = '<button type="submit" class="btn btn-primary mb-2" name="update" id="update" data-toggle="modal" data-target="#exampleModal">change</button>';
        foreach ($res as $rem) {
            // 计算剩余到期天数(单位:天)
            $expire = (strtotime($rem[2]) / 86400) - (strtotime("now") / 86400);
            
            // 修正顺序后的状态类判断
            if ($expire <= 0) {
                $row_class = 'expired';
            } elseif ($expire <= 30) {
                $row_class = 'expiring';
            } else {
                $row_class = 'active';
            }

            // 渲染行的时候把类名挂到<tr>上
            echo  "<tr class='{$row_class}'>
                <td>" . $rem[0] . "</td>
                <td>" . $rem[1] . "</td>
                <td>" . $rem[2] . "</td>
                <td>" . $rem[3] . "</td>
                <td>" . $rem[4] . "</td>
                <td>" . $rem[5] . "</td>
                <td>" . $button_upd . "</td>                   
                </tr>";
        }
        ?>
        </tbody>
    </table>
</div>

配套的样式优化提示

因为页面引入了Bootstrap的table table-hover类,默认的表格行样式可能会覆盖自定义的背景色,建议把原CSS选择器的优先级提高,避免样式失效:

/* 提高选择器优先级,确保自定义样式覆盖Bootstrap默认样式 */
tbody tr.expiring{
    background-color: yellow !important;
    color: black !important;
}
tbody tr.expired{
    background-color: red !important;
    color: white !important;
}
tbody tr.active{
    background-color: green !important;
    color: white !important;
}

内容的提问来源于stack exchange,提问作者Beka Shvelidze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.08 20:06:04