蓝色天空.知识 · 实践 · 创造
我的收藏
jQuery EasyUI 教程目录 68章
课程介绍
jQuery EasyUI / LEARN BY DOING

jEasyUI 创建列组合

核对使用平面 JSON 数据配合双行 thead(rowspan="2" 与 colspan="4")将多列归并到统一父级分组表头下的结构与几何离线实测。

学完这一章,你能够

  • 核对使用平面 JSON 数据配合双行 thead(rowspan="2" 与 colspan="4")将多列归并到统一父级分组表头下的结构与几何离线实测。

使用平面数据与双行表头创建列组合

在展示包含多个关联明细字段的平面 JSON 数据时,DataGrid 允许在 `columns` 或 `<thead>` 中通过 `rowspan` 与 `colspan` 组合表头单元格,而无需改动底层平面数据结构。具体实现为:第一行表头将 `Item ID`(`itemid`)与 `Product ID`(`productid`)设为 `rowspan="2"`,右侧用 `<th colspan="4">Item Details</th>` 合并四列;第二行再依次声明 `listprice`、`unitcost`、`attr1`(说明文字常写作地址/属性列)与 `status` 四个子列,并开启 `rownumbers="true"` 与 `singleSelect="true"`。本站 Chromium 离线实测核验:双行表头正确解析出 6 个叶子字段,平面数据每行准确渲染为“行号 + 6 个数据单元格”,`Item Details` 渲染宽度与下方 4 个子列总宽精确对齐(误差 ≤ 2px),且单选点击仅高亮当前行。

参考示例压缩包 `jeasyui-datagrid-datagrid9.zip` 遵循来源站访问停止状态未联网下载并已登记于附件清单;通过本地离线 Chromium 脚本可直接核验列组合表头结构与宽度对齐。

运行 DataGrid 列组合表头(rowspan/colspan)与平面数据映射的离线 Chromium 实验

含完整源码 · 155 行
展开查看收起
python
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 31: Column Group."""
import json
from playwright.sync_api import sync_playwright

HTML_DOC = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>EasyUI Column Group Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 12px; }
  .dg-panel { width: 550px; border: 1px solid #95b8e7; box-sizing: border-box; }
  .dg-title { background: #e0ecff; padding: 6px 8px; font-weight: 600; font-size: 13px; border-bottom: 1px solid #95b8e7; }
  table { width: 100%; border-collapse: collapse; table-layout: fixed; font-size: 12px; }
  th, td { border: 1px solid #ccc; padding: 4px 6px; box-sizing: border-box; }
  th { background: #efefef; }
  tr.dg-row { cursor: pointer; }
  tr.dg-row.selected { background: #ffe48d; }
</style>
</head>
<body>
<div class="dg-panel">
  <div class="dg-title">Column Group</div>
  <table id="tt" title="Column Group" singleSelect="true" iconCls="icon-save" rownumbers="true">
    <thead>
      <tr>
        <th rowspan="2" width="28">#</th>
        <th rowspan="2" field="itemid" width="80">Item ID</th>
        <th rowspan="2" field="productid" width="80">Product ID</th>
        <th colspan="4" id="grp-details">Item Details</th>
      </tr>
      <tr>
        <th field="listprice" width="80" align="right">List Price</th>
        <th field="unitcost" width="80" align="right">Unit Cost</th>
        <th field="attr1" width="100">Attribute</th>
        <th field="status" width="60" align="center">Status</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>
<script>
const FLAT_DATA = [
  { itemid: "EST-1", productid: "FI-SW-01", listprice: 16.5, unitcost: 10.0, attr1: "Large", status: "P" },
  { itemid: "EST-10", productid: "K9-DL-01", listprice: 18.5, unitcost: 12.0, attr1: "Spotted", status: "P" },
  { itemid: "EST-11", productid: "RP-SN-01", listprice: 28.5, unitcost: 12.0, attr1: "Venomless", status: "P" },
];

const leafHeaders = Array.from(document.querySelectorAll('#tt thead th[field]'));
const tbody = document.querySelector('#tt tbody');
FLAT_DATA.forEach((row, idx) => {
  const tr = document.createElement('tr');
  tr.className = 'dg-row';
  tr.dataset.itemid = row.itemid;
  let html = `<td style="text-align:center">${idx + 1}</td>`;
  leafHeaders.forEach(th => {
    const f = th.getAttribute('field');
    const align = th.getAttribute('align');
    html += `<td data-field="${f}" style="${align ? 'text-align:' + align : ''}">${row[f]}</td>`;
  });
  tr.innerHTML = html;
  tr.addEventListener('click', () => {
    tbody.querySelectorAll('tr.selected').forEach(el => el.classList.remove('selected'));
    tr.classList.add('selected');
  });
  tbody.appendChild(tr);
});
</script>
</body>
</html>
"""


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 680, "height": 420})
        page.set_content(HTML_DOC)

        # Case 1: 2-row header with rowspan=2 and colspan=4 over 6 leaf fields
        res1 = page.evaluate("""() => {
            const rows = Array.from(document.querySelectorAll('#tt thead tr'));
            const row0 = Array.from(rows[0].querySelectorAll('th')).map(th => ({
                text: th.textContent.trim(),
                field: th.getAttribute('field'),
                rowspan: th.rowSpan,
                colspan: th.colSpan,
            }));
            const row1Fields = Array.from(rows[1].querySelectorAll('th')).map(th => th.getAttribute('field'));
            const leafFields = Array.from(document.querySelectorAll('#tt thead th[field]')).map(th => th.getAttribute('field'));
            return { headerRowCount: rows.length, row0, row1Fields, leafFields };
        }""")
        exp1 = {
            "headerRowCount": 2,
            "row0": [
                {"text": "#", "field": None, "rowspan": 2, "colspan": 1},
                {"text": "Item ID", "field": "itemid", "rowspan": 2, "colspan": 1},
                {"text": "Product ID", "field": "productid", "rowspan": 2, "colspan": 1},
                {"text": "Item Details", "field": None, "rowspan": 1, "colspan": 4},
            ],
            "row1Fields": ["listprice", "unitcost", "attr1", "status"],
            "leafFields": ["itemid", "productid", "listprice", "unitcost", "attr1", "status"],
        }
        cases.append(dict(name="column_group_rowspan_colspan_structure", expected=exp1, actual=res1, passed=(res1 == exp1)))

        # Case 2: Flat JSON data maps cleanly across row number + 6 leaf cells
        res2 = page.evaluate("""() => {
            const firstTr = document.querySelector('#tt tbody tr:first-child');
            const tds = Array.from(firstTr.querySelectorAll('td'));
            return {
                rowCount: document.querySelectorAll('#tt tbody tr').length,
                cellCount: tds.length,
                firstRowTexts: tds.map(td => td.textContent.trim()),
                firstRowFields: tds.slice(1).map(td => td.dataset.field),
            };
        }""")
        exp2 = {
            "rowCount": 3,
            "cellCount": 7,
            "firstRowTexts": ["1", "EST-1", "FI-SW-01", "16.5", "10", "Large", "P"],
            "firstRowFields": ["itemid", "productid", "listprice", "unitcost", "attr1", "status"],
        }
        cases.append(dict(name="flat_data_mapping_under_grouped_header", expected=exp2, actual=res2, passed=(res2 == exp2)))

        # Case 3: Group header bounding width equals sum of 4 child headers & singleSelect works
        page.click('tr.dg-row[data-itemid="EST-1"]')
        page.click('tr.dg-row[data-itemid="EST-11"]')
        res3 = page.evaluate("""() => {
            const grpW = document.getElementById('grp-details').getBoundingClientRect().width;
            const childSum = Array.from(document.querySelectorAll('#tt thead tr:nth-child(2) th'))
                .reduce((s, th) => s + th.getBoundingClientRect().width, 0);
            const selected = Array.from(document.querySelectorAll('#tt tbody tr.selected')).map(tr => tr.dataset.itemid);
            return {
                groupCoversFourChildren: Math.abs(grpW - childSum) <= 2,
                singleSelectedIds: selected,
            };
        }""")
        exp3 = {"groupCoversFourChildren": True, "singleSelectedIds": ["EST-11"]}
        cases.append(dict(name="group_header_bounding_geometry_and_single_select", expected=exp3, actual=res3, passed=(res3 == exp3)))

        browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对 2 行表头 rowspan=2/colspan=4 结构、平面数据 7 单元格(含行号)准确映射、分组头宽度覆盖 4 子列及 singleSelect 单选高亮。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a989.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:jQuery EasyUI

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a989.zip

下载课程关联工程包:jQuery EasyUI

课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

不需要。列组合仅是表头层的视觉分组,叶子列仍直接按各自的 `field` 键读取平面 JSON 记录中的字段值。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习