蓝色天空网mbsky.com · 知识 · 实践 · 创造jQuery EasyUI · 本地阅读预览
教程 / 前端开发 / jQuery EasyUI

jEasyUI 合并单元格

核对 DataGrid 冻结列与双行分组表头配置,以及在 onLoadSuccess 回调中调用 mergeCells 实现纵向 rowspan 与横向 colspan 单元格合并。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

mergeCells 合并原理与冻结双行表头

当表格中相邻行或相邻列存在重复归类信息时,可调用 DataGrid 的 `mergeCells` 方法传入起始行索引 `index`、字段名 `field` 以及跨行数 `rowspan` 或跨列数 `colspan`。其核心渲染机制是增大起始单元格的 `rowSpan`/`colSpan` 属性,并将被覆盖的其余单元格设置为隐藏(`display: none`),而非直接从 DOM 删除,从而保持后续索引稳定。

示例网格同时配置了左侧冻结表头 `<thead frozen="true">`(包含 `productid` 与 `itemid`)以及右侧双行组合表头(`Price` 跨 2 列覆盖 `listprice` 与 `unitcost`,`Attribute` 与 `Status` 各自跨 2 行;注:原示例表头文字 `Stauts` 为拼写笔误,工程中应规范为 `Status`),并开启行号与分页栏。本站离线实测确认表头共 `2` 行、冻结列为 `['productid', 'itemid']`、`Price` 的 `colSpan = 2` 且 `Attribute` 的 `rowSpan = 2`。

在 onLoadSuccess 中批量合并单元格实测

由于合并操作依赖已渲染的行 DOM,必须在数据加载完成后的 `onLoadSuccess` 回调内遍历配置数组(`index: 2/5/7` 各自 `rowspan: 2`)逐一调用 `mergeCells`。本站无头浏览器加载 10 行商品数据并执行合并后实测:第 `2`、`5`、`7` 行的 `productid` 单元格 `rowSpan` 均为 `2` 且保持 `table-cell` 可见,而被覆盖的第 `3`、`6`、`8` 行对应单元格仍留在 DOM(共 `10` 个单元格,可见 `7` 个)且计算样式均为 `display: none`;另验证横向 `mergeCells({index:0, field:'listprice', colspan:2})` 后,`listprice` 的 `colSpan = 2`、`unitcost` 隐藏,且跨两行合并格高度显著高于单行格。

来源压缩包 `jeasyui-datagrid-datagrid13.zip` 未联网下载,已通过本地无头 Chromium 实验核对多行表头与纵横合并行为。

运行 DataGrid 双行冻结表头与 mergeCells 纵横合并离线实验

python · 阅读源码
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 37: DataGrid Merge Cells."""
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 DataGrid Merge Cells Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 16px; font-size: 13px; }
  .dg-box { width: 550px; border: 1px solid #95b8e7; }
  .dg-title { background: #e0ecff; padding: 6px 8px; font-weight: bold; }
  table#tt { width: 100%; border-collapse: collapse; }
  table#tt th, table#tt td { border: 1px solid #ccc; padding: 4px 6px; height: 24px; box-sizing: border-box; }
  table#tt th { background: #f4f4f4; }
  .frozen-col { background: #fafafa; }
  .dg-pager { background: #f4f4f4; padding: 4px 8px; border-top: 1px solid #ccc; font-size: 12px; }
</style>
</head>
<body>
<div class="dg-box">
  <div class="dg-title">Merge Cells</div>
  <table id="tt">
    <thead>
      <tr>
        <th rowspan="2" data-role="rownumber">#</th>
        <th rowspan="2" data-frozen="true" data-field="productid">Product ID</th>
        <th rowspan="2" data-frozen="true" data-field="itemid">Item ID</th>
        <th colspan="2" data-group="Price">Price</th>
        <th rowspan="2" data-field="attr1">Attribute</th>
        <th rowspan="2" data-field="status">Status</th>
      </tr>
      <tr>
        <th data-field="listprice">List Price</th>
        <th data-field="unitcost">Unit Cost</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
  <div class="dg-pager">Page 1 of 1 (10 items)</div>
</div>

<script>
const colOrder = ["productid", "itemid", "listprice", "unitcost", "attr1", "status"];
const rows = [
  { productid: "FI-SW-01", itemid: "EST-1", listprice: 16.5, unitcost: 10, attr1: "Large", status: "P" },
  { productid: "K9-DL-01", itemid: "EST-10", listprice: 18.5, unitcost: 12, attr1: "Spotted Adult Female", status: "P" },
  { productid: "RP-SN-01", itemid: "EST-11", listprice: 18.5, unitcost: 12, attr1: "Venomless", status: "P" },
  { productid: "RP-SN-01", itemid: "EST-12", listprice: 18.5, unitcost: 12, attr1: "Rattleless", status: "P" },
  { productid: "RP-LI-02", itemid: "EST-13", listprice: 18.5, unitcost: 12, attr1: "Green Adult", status: "P" },
  { productid: "FL-DSH-01", itemid: "EST-14", listprice: 58.5, unitcost: 12, attr1: "Tailless", status: "P" },
  { productid: "FL-DSH-01", itemid: "EST-15", listprice: 23.5, unitcost: 12, attr1: "With tail", status: "P" },
  { productid: "FL-DLH-02", itemid: "EST-16", listprice: 93.5, unitcost: 12, attr1: "Adult Female", status: "P" },
  { productid: "FL-DLH-02", itemid: "EST-17", listprice: 93.5, unitcost: 12, attr1: "Adult Male", status: "P" },
  { productid: "AV-CB-01", itemid: "EST-18", listprice: 193.5, unitcost: 92, attr1: "Adult Male", status: "P" }
];

function renderRows() {
  const tbody = document.querySelector("#tt tbody");
  tbody.innerHTML = "";
  rows.forEach((row, idx) => {
    const tr = document.createElement("tr");
    tr.dataset.index = String(idx);
    const rn = document.createElement("td");
    rn.textContent = String(idx + 1);
    rn.className = "frozen-col";
    tr.appendChild(rn);
    colOrder.forEach(field => {
      const td = document.createElement("td");
      td.dataset.field = field;
      if (field === "productid" || field === "itemid") td.className = "frozen-col";
      td.textContent = String(row[field]);
      tr.appendChild(td);
    });
    tbody.appendChild(tr);
  });
}

function mergeCells(opts) {
  const startRow = opts.index;
  const field = opts.field;
  const rowspan = opts.rowspan || 1;
  const colspan = opts.colspan || 1;
  const startColIdx = colOrder.indexOf(field);
  const firstTd = document.querySelector(`#tt tbody tr[data-index="${startRow}"] td[data-field="${field}"]`);
  if (!firstTd) return;
  if (rowspan > 1) firstTd.rowSpan = rowspan;
  if (colspan > 1) firstTd.colSpan = colspan;
  for (let r = startRow; r < startRow + rowspan; r++) {
    for (let c = startColIdx; c < startColIdx + colspan; c++) {
      if (r === startRow && c === startColIdx) continue;
      const hiddenTd = document.querySelector(`#tt tbody tr[data-index="${r}"] td[data-field="${colOrder[c]}"]`);
      if (hiddenTd) hiddenTd.style.display = "none";
    }
  }
}

renderRows();
// Exact onLoadSuccess merges from source
const merges = [
  { index: 2, rowspan: 2 },
  { index: 5, rowspan: 2 },
  { index: 7, rowspan: 2 }
];
for (let i = 0; i < merges.length; i++) {
  mergeCells({ index: merges[i].index, field: "productid", rowspan: merges[i].rowspan });
}

window.lab = { mergeCells };
</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()
        page.set_content(HTML_DOC)

        # Case 1: Frozen columns + multi-row grouped Price header + pager
        res1 = page.evaluate("""() => {
            const frozenFields = Array.from(document.querySelectorAll('#tt thead th[data-frozen="true"]')).map(el => el.dataset.field);
            const priceTh = document.querySelector('#tt thead th[data-group="Price"]');
            const attrTh = document.querySelector('#tt thead th[data-field="attr1"]');
            return {
                headerRowCount: document.querySelectorAll('#tt thead tr').length,
                frozenFields,
                priceColSpan: priceTh.colSpan,
                attrRowSpan: attrTh.rowSpan,
                hasPager: document.querySelector('.dg-pager') !== null
            };
        }""")
        exp1 = {
            "headerRowCount": 2,
            "frozenFields": ["productid", "itemid"],
            "priceColSpan": 2,
            "attrRowSpan": 2,
            "hasPager": True,
        }
        cases.append(dict(name="frozen_and_multi_row_header_structure", expected=exp1, actual=res1, passed=(res1 == exp1)))

        # Case 2: onLoadSuccess rowspan merges hide covered cells without detaching them
        res2 = page.evaluate("""() => {
            const check = (idx) => {
                const td = document.querySelector(`#tt tbody tr[data-index="${idx}"] td[data-field="productid"]`);
                return { rowSpan: td.rowSpan, display: getComputedStyle(td).display, text: td.textContent };
            };
            const mergedTops = [2, 5, 7].map(check);
            const coveredHidden = [3, 6, 8].map(check);
            const visibleCount = Array.from(document.querySelectorAll('#tt tbody td[data-field="productid"]'))
                .filter(td => getComputedStyle(td).display !== "none").length;
            const domCount = document.querySelectorAll('#tt tbody td[data-field="productid"]').length;
            return { mergedTops, coveredHidden, visibleCount, domCount };
        }""")
        exp2 = {
            "mergedTops": [
                {"rowSpan": 2, "display": "table-cell", "text": "RP-SN-01"},
                {"rowSpan": 2, "display": "table-cell", "text": "FL-DSH-01"},
                {"rowSpan": 2, "display": "table-cell", "text": "FL-DLH-02"},
            ],
            "coveredHidden": [
                {"rowSpan": 1, "display": "none", "text": "RP-SN-01"},
                {"rowSpan": 1, "display": "none", "text": "FL-DSH-01"},
                {"rowSpan": 1, "display": "none", "text": "FL-DLH-02"},
            ],
            "visibleCount": 7,
            "domCount": 10,
        }
        cases.append(dict(name="onloadsuccess_mergecells_rowspan", expected=exp2, actual=res2, passed=(res2 == exp2)))

        # Case 3: Colspan merge and merged cell vertical height check
        res3 = page.evaluate("""() => {
            window.lab.mergeCells({ index: 0, field: "listprice", colspan: 2 });
            const lp = document.querySelector('#tt tbody tr[data-index="0"] td[data-field="listprice"]');
            const uc = document.querySelector('#tt tbody tr[data-index="0"] td[data-field="unitcost"]');
            const mergedH = Math.round(document.querySelector('#tt tbody tr[data-index="2"] td[data-field="productid"]').getBoundingClientRect().height);
            const singleH = Math.round(document.querySelector('#tt tbody tr[data-index="0"] td[data-field="productid"]').getBoundingClientRect().height);
            return {
                listpriceColSpan: lp.colSpan,
                unitcostDisplay: getComputedStyle(uc).display,
                mergedHeightGreaterThanSingle: mergedH > singleH + 15
            };
        }""")
        exp3 = {
            "listpriceColSpan": 2,
            "unitcostDisplay": "none",
            "mergedHeightGreaterThanSingle": True,
        }
        cases.append(dict(name="mergecells_colspan_and_bounds", expected=exp3, actual=res3, passed=(res3 == exp3)))

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


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 2 行表头结构、index=2/5/7 行 productid 跨两行合并且覆盖格 display:none(DOM 共 10 格可见 7 格),以及 listprice 横向 colspan=2。
运行 DataGrid 双行冻结表头与 mergeCells 纵横合并离线实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:4930e7173282d7af33870deeb3f02a7d0fbd79e879d7f7139fc88066c3623b49

下载本站示例源码

本地运行

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

下载jEasyUI 合并单元格实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:d0b2c3dc0f2da2960420e6254a6c95d8c64c226b65896ba17fcc84dec179c5fc

常见错误与边界

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

练习与解答

为什么 mergeCells 应当放在 onLoadSuccess 回调中执行,被合并覆盖的单元格会发生什么变化?

展开参考解答

因为数据异步加载并渲染出表格行 DOM 后才能定位目标单元格,每次翻页或刷新也会重绘表格;mergeCells 会将首个单元格的 rowSpan/colSpan 扩大,并将其余被覆盖单元格隐藏(display:none)而非删除。

规范与官方依据