jEasyUI 创建子网格
核对利用 detailview 在主网格展开行中动态挂载嵌套子网格(SubGrid)的配置、主从双接口过滤及 onLoadSuccess/onResize 行高修正实测。
学完这一章,你能够
- 核对利用 detailview 在主网格展开行中动态挂载嵌套子网格(SubGrid)的配置、主从双接口过滤及 onLoadSuccess/onResize 行高修正实测。
主网格定义与 detailview 嵌套子网格配置
由于 DataGrid 详细视图允许在展开容器内嵌入任意组件,把另一个 DataGrid 挂载到展开区即可实现典型的主从表(SubGrid)交互。先按常规方式定义主网格(展示商品基础字段并绑定主列表接口)。
引入 `datagrid-detailview.js` 后,将 `detailFormatter` 改为返回 `<div style="padding:2px"><table class="ddv"></table></div>` 作为子表宿主。当点击 `+` 触发 `onExpandRow(index, row)` 时,定位当前行的 `table.ddv` 并初始化包含 `orderid`、`quantity`、`unitprice` 三列的子 DataGrid(携带 `?itemid=` 参数请求订单明细,关闭加载遮罩并设 `height:'auto'`)。关键点在于子表加载成功(在 `onLoadSuccess` 内用 `setTimeout(..., 0)` 延后到 DOM 绘制完毕)以及尺寸变化(`onResize`)时都必须回调主表的 `fixDetailRowHeight(index)` 以重新对齐行高。
主从双接口与多行并发子网格实测
服务端由两个接口配合:主接口筛选存在订单明细的商品列表(`itemid IN (SELECT itemid FROM lineitem)`),明细接口按 `itemid` 返回对应订单行 JSON(同样需在生产中以 PDO 预处理替代历史 PHP `mysql_*` 函数)。本站通过本地 `127.0.0.1` 回环服务与无头 Chromium 实测:主表自动过滤掉无订单的 `EST-99`,仅加载 `['EST-1', 'EST-2', 'EST-3']` 共 3 条主记录;展开 `EST-1` 后嵌套子表渲染 `['#', 'Order ID', 'Quantity', 'Unit Price']` 表头与 `['ORD-1001', 'ORD-1002', 'ORD-1005']` 3 条订单,并依次记录 `['onExpandRow', 'onLoadSuccess', 'onResize']` 三次高度修正;同时展开 `EST-2`(2 条订单)并在两张子表分别点选记录时,各自独立保持单选状态且 `EST-1` 展开区高度严格大于 `EST-2`。
来源压缩包 `jeasyui-datagrid-datagrid22.zip` 未联网下载,已由本地回环服务与无头浏览器实验完整验证主从过滤与多子表并行交互。
运行 DataGrid 主从嵌套子网格与行高同步离线回环实验
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 43: DataGrid SubGrid."""
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import threading
from urllib.parse import parse_qs, urlparse
from playwright.sync_api import sync_playwright
ALL_ITEMS = [
{"itemid": "EST-1", "productid": "FI-SW-01", "listprice": "16.50", "unitcost": "10.00", "attr1": "Large", "status": "P"},
{"itemid": "EST-2", "productid": "K9-DL-01", "listprice": "18.50", "unitcost": "12.00", "attr1": "Spotted Adult Female", "status": "P"},
{"itemid": "EST-3", "productid": "RP-SN-01", "listprice": "18.50", "unitcost": "12.00", "attr1": "Venomless", "status": "P"},
{"itemid": "EST-99", "productid": "ORPHAN-01", "listprice": "9.00", "unitcost": "4.00", "attr1": "No Orders", "status": "P"},
]
LINEITEMS = [
{"itemid": "EST-1", "orderid": "ORD-1001", "quantity": 2, "unitprice": "16.50"},
{"itemid": "EST-1", "orderid": "ORD-1002", "quantity": 5, "unitprice": "16.00"},
{"itemid": "EST-1", "orderid": "ORD-1005", "quantity": 1, "unitprice": "16.50"},
{"itemid": "EST-2", "orderid": "ORD-1003", "quantity": 3, "unitprice": "18.50"},
{"itemid": "EST-2", "orderid": "ORD-1004", "quantity": 4, "unitprice": "18.00"},
{"itemid": "EST-3", "orderid": "ORD-1006", "quantity": 2, "unitprice": "18.50"},
]
HTML_PAGE = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>EasyUI DataGrid SubGrid Offline Lab</title>
<style>
body { font-family: sans-serif; margin: 16px; font-size: 13px; }
.dg-wrap { width: 700px; border: 1px solid #95b8e7; }
.dg-title { background: #e0ecff; padding: 6px 8px; font-weight: bold; }
table#dg, table.ddv { width: 100%; border-collapse: collapse; }
table#dg th, table#dg td, table.ddv th, table.ddv td { border: 1px solid #ccc; padding: 4px 6px; }
table#dg th { background: #f4f4f4; }
table.ddv th { background: #eef6ff; }
table.ddv tbody tr { cursor: pointer; }
table.ddv tbody tr.selected { background: #ffe48d; }
tr.detail-row.hidden { display: none; }
.expander { width: 20px; height: 20px; cursor: pointer; font-weight: bold; }
</style>
</head>
<body>
<div class="dg-wrap">
<div class="dg-title">DataGrid - SubGrid</div>
<table id="dg">
<thead>
<tr>
<th style="width:28px"></th>
<th>Item ID</th><th>Product ID</th><th>List Price</th><th>Unit Cost</th><th>Attribute</th><th>Status</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script>
const fixCalls = [];
function fixDetailRowHeight(index, reason) {
const dtr = document.querySelector(`tr.detail-row[data-index="${index}"]`);
const h = Math.round(dtr.querySelector(".detail-wrap").getBoundingClientRect().height);
dtr.dataset.fixedHeight = String(h);
fixCalls.push({ index, reason, height: h });
}
async function mountSubGrid(tableEl, index, itemid) {
const resp = await fetch(`/datagrid22_getdetail?itemid=${encodeURIComponent(itemid)}`);
const rows = await resp.json();
tableEl.innerHTML = `
<thead><tr><th style="width:28px">#</th><th>Order ID</th><th>Quantity</th><th>Unit Price</th></tr></thead>
<tbody></tbody>`;
const tbody = tableEl.querySelector("tbody");
rows.forEach((r, i) => {
const tr = document.createElement("tr");
tr.dataset.orderid = r.orderid;
tr.innerHTML = `<td>${i + 1}</td><td>${r.orderid}</td><td>${r.quantity}</td><td>${r.unitprice}</td>`;
tr.addEventListener("click", () => {
tbody.querySelectorAll("tr").forEach(el => el.classList.remove("selected"));
tr.classList.add("selected");
});
tbody.appendChild(tr);
});
tableEl.dataset.loaded = "true";
setTimeout(() => fixDetailRowHeight(index, "onLoadSuccess"), 0);
}
async function initMaster() {
const resp = await fetch("/datagrid22_getdata");
const rows = await resp.json();
const tbody = document.querySelector("#dg tbody");
tbody.innerHTML = "";
rows.forEach((row, index) => {
const tr = document.createElement("tr");
tr.className = "master-row";
tr.dataset.index = String(index);
tr.dataset.itemid = row.itemid;
tr.innerHTML = `
<td style="text-align:center"><button type="button" class="expander" data-index="${index}">+</button></td>
<td>${row.itemid}</td><td>${row.productid}</td>
<td style="text-align:right">${row.listprice}</td><td style="text-align:right">${row.unitcost}</td>
<td>${row.attr1}</td><td style="text-align:center">${row.status}</td>`;
const dtr = document.createElement("tr");
dtr.className = "detail-row hidden";
dtr.dataset.index = String(index);
dtr.innerHTML = `<td colspan="7"><div class="detail-wrap" style="padding:2px"><table class="ddv" data-parent="${row.itemid}"></table></div></td>`;
tbody.append(tr, dtr);
tr.querySelector(".expander").addEventListener("click", async (ev) => {
const btn = ev.currentTarget;
if (btn.textContent === "-") {
btn.textContent = "+";
dtr.classList.add("hidden");
return;
}
btn.textContent = "-";
dtr.classList.remove("hidden");
fixDetailRowHeight(index, "onExpandRow");
const subTable = dtr.querySelector("table.ddv");
await mountSubGrid(subTable, index, row.itemid);
});
});
window.__masterReady = true;
}
window.lab = { fixCalls, triggerResize: (index) => fixDetailRowHeight(index, "onResize") };
initMaster();
</script>
</body>
</html>
"""
class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
pass
def do_GET(self):
parsed = urlparse(self.path)
if parsed.path == "/":
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write(HTML_PAGE.encode("utf-8"))
elif parsed.path == "/datagrid22_getdata":
# Mirrors: select * from item where itemid in (select itemid from lineitem)
linked = {li["itemid"] for li in LINEITEMS}
matched = [it for it in ALL_ITEMS if it["itemid"] in linked]
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(matched).encode("utf-8"))
elif parsed.path == "/datagrid22_getdetail":
itemid = parse_qs(parsed.query).get("itemid", [""])[0]
matched = [li for li in LINEITEMS if li["itemid"] == itemid]
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(matched).encode("utf-8"))
else:
self.send_response(404)
self.end_headers()
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
server = HTTPServer(("127.0.0.1", 0), Handler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
cases = []
try:
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.goto(f"http://127.0.0.1:{port}/")
page.wait_for_function("() => window.__masterReady === true")
# Case 1: Master grid filters to items having lineitems and embeds table.ddv placeholders
res1 = page.evaluate("""() => ({
masterIds: Array.from(document.querySelectorAll("tr.master-row")).map(r => r.dataset.itemid),
subTableCount: document.querySelectorAll("table.ddv").length
})""")
exp1 = {"masterIds": ["EST-1", "EST-2", "EST-3"], "subTableCount": 3}
cases.append(dict(name="subgrid_master_load_and_detail_formatter", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: Expanding row 0 loads 3-column nested DataGrid and triggers fixDetailRowHeight
page.click('.expander[data-index="0"]')
page.wait_for_selector('table.ddv[data-parent="EST-1"][data-loaded="true"]')
page.wait_for_function("() => window.lab.fixCalls.some(c => c.index === 0 && c.reason === 'onLoadSuccess')")
page.evaluate("() => window.lab.triggerResize(0)")
res2 = page.evaluate("""() => {
const sub = document.querySelector('table.ddv[data-parent="EST-1"]');
const headers = Array.from(sub.querySelectorAll(":scope > thead > tr > th")).map(th => th.textContent);
const orderIds = Array.from(sub.querySelectorAll(":scope > tbody > tr")).map(tr => tr.dataset.orderid);
const reasons = window.lab.fixCalls.filter(c => c.index === 0).map(c => c.reason);
return { headers, orderIds, fixReasons: reasons };
}""")
exp2 = {
"headers": ["#", "Order ID", "Quantity", "Unit Price"],
"orderIds": ["ORD-1001", "ORD-1002", "ORD-1005"],
"fixReasons": ["onExpandRow", "onLoadSuccess", "onResize"],
}
cases.append(dict(name="subgrid_expand_loads_nested_datagrid", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: Multi-expand keeps independent singleSelect state and distinct detail heights
page.click('.expander[data-index="1"]')
page.wait_for_selector('table.ddv[data-parent="EST-2"][data-loaded="true"]')
page.wait_for_function("() => window.lab.fixCalls.some(c => c.index === 1 && c.reason === 'onLoadSuccess')")
page.click('table.ddv[data-parent="EST-1"] tbody tr[data-orderid="ORD-1002"]')
page.click('table.ddv[data-parent="EST-2"] tbody tr[data-orderid="ORD-1004"]')
res3 = page.evaluate("""() => {
const s0 = document.querySelector('table.ddv[data-parent="EST-1"] tbody tr.selected').dataset.orderid;
const s1 = document.querySelector('table.ddv[data-parent="EST-2"] tbody tr.selected').dataset.orderid;
const h0 = Number(document.querySelector('tr.detail-row[data-index="0"]').dataset.fixedHeight);
const h1 = Number(document.querySelector('tr.detail-row[data-index="1"]').dataset.fixedHeight);
return {
sub0Selected: s0,
sub1Selected: s1,
sub0TallerThanSub1: h0 > h1
};
}""")
exp3 = {"sub0Selected": "ORD-1002", "sub1Selected": "ORD-1004", "sub0TallerThanSub1": True}
cases.append(dict(name="subgrid_independent_selection_and_multi_expand", expected=exp3, actual=res3, passed=(res3 == exp3)))
browser.close()
finally:
server.shutdown()
server.server_close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对主表过滤无明细商品、展开 EST-1 加载 3 条订单并触发 onExpandRow/onLoadSuccess/onResize 行高修正,以及双子表独立单选。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:edade7e202eb030f3cb6041ea39fcfba2ae25364566493860fed70219f040180
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:c95fd8b29eb611eac4faab310b57707fa18ee84633a7142d3ae813f3d0da0e0c
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在子网格的 onLoadSuccess 回调里为什么常常要用 setTimeout(..., 0) 包裹主表的 fixDetailRowHeight 调用?
展开参考解答
因为 onLoadSuccess 触发瞬间浏览器可能尚未完成嵌套子表列宽自适应与最终高度回流,借助 setTimeout(..., 0) 将高度修正排到当前渲染周期之后,可读取到准确的展开容器高度。