You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bootstrap表格行无法垂直对应表头,请求技术解决方案

问题:Bootstrap表格行与表头垂直对齐异常

我在个人项目中通过数据库数据生成Bootstrap表格,期望表格行能垂直对应表头显示,但当前效果不符合预期,尝试了多种同类问题的解决方案均无效,恳请帮忙找出问题并解决。

当前EJS代码

<table class="table table-bordered table-striped">
    <thead>
        <tr>
            <% groups.forEach((group) => { %>
                <th><%= group.name %></th>
            <% }) %>
        </tr>
    </thead>
    <tbody>
        <% groups.forEach((group) => { %>
            <tr>
                <% group.items.forEach((item) => { %>
                    <% if(item.name === group.overseer.name){ %>
                        <td><strong><%= item.name %></strong></td>
                    <% } else { %>
                        <td><%= item.name %></td>
                    <% } %>
                <% }) %>
            </tr>
        <% }) %>
    </tbody>
</table>

当前显示效果

当前显示效果

期望显示效果

期望显示效果

问题原因与解决方案

问题分析

原代码逻辑错误:遍历每个group生成一行,再把该group的所有items依次放入这一行的单元格中。这导致每个group对应一行,单元格数量等于该group的成员数,完全不符合表头(每列对应一个group)的垂直对齐要求。

正确逻辑应该是:按行索引遍历,每一行对应所有group的第N个成员,若某个group没有第N个成员,则显示空单元格。

修正后的EJS代码

<table class="table table-bordered table-striped">
    <thead>
        <tr>
            <% groups.forEach((group) => { %>
                <th><%= group.name %></th>
            <% }) %>
        </tr>
    </thead>
    <tbody>
        <% 
            // 计算所有分组中成员的最大数量,确定表格行数
            const maxRowCount = Math.max(...groups.map(g => g.items.length));
            // 遍历每一行索引
            for(let rowIndex = 0; rowIndex < maxRowCount; rowIndex++) {
        %>
            <tr>
                <% 
                    // 遍历每个分组,取当前行索引对应的成员
                    groups.forEach((group) => {
                        const item = group.items[rowIndex];
                %>
                    <% if(item) { %>
                        <% if(item.name === group.overseer.name){ %>
                            <td><strong><%= item.name %></strong></td>
                        <% } else { %>
                            <td><%= item.name %></td>
                        <% } %>
                    <% } else { %>
                        <!-- 无对应成员时显示空单元格 -->
                        <td></td>
                    <% } %>
                <% }) %>
            </tr>
        <% } %>
    </tbody>
</table>

代码说明

  1. 先通过Math.max(...groups.map(g => g.items.length))计算所有分组的成员数量最大值,确定表格需要的总行数。
  2. 按行索引循环,每一行内遍历所有分组:
    • 取出当前分组对应行索引的成员item
    • 若成员存在,按原逻辑显示(管理员名称加粗);若不存在,输出空单元格<td></td>,保证每一行的单元格数量与表头列数一致,实现垂直对齐。

内容的提问来源于stack exchange,提问作者Maciej Kuta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 07:30:07