jEasyUI 扩展行显示细节
核对 datagrid-detailview.js 详细视图的展开按钮、detailFormatter 容器、onExpandRow 异步加载面板与 fixDetailRowHeight 高度修正实测。
学完这一章,你能够
- 核对 datagrid-detailview.js 详细视图的展开按钮、detailFormatter 容器、onExpandRow 异步加载面板与 fixDetailRowHeight 高度修正实测。
配置主表格与引入 detailview 扩展
借助 DataGrid 的详细视图(Detail View)扩展,数据行左侧会自动增加 `+`/`-` 展开图标,点击即可在行下方滑出附加详情区。第一步先创建常规主表格(定义 `itemid`、`productid`、`listprice`、`unitcost`、`status` 列并开启分页与默认降序)。
第二步需在页面头部引入官方扩展脚本 `datagrid-detailview.js`,并在初始化配置中设置 `view: detailview`:`detailFormatter` 返回初始为空的 `<div class="ddv" style="padding:5px 0"></div>` 容器;当用户点击 `+` 触发 `onExpandRow(index, row)` 时,通过 `getRowDetail(index)` 定位该容器并初始化无边框、禁用缓存(`cache: false`)的 `panel`,通过 `href` 异步请求详情片段;在 `onLoad` 回调及展开瞬间都应调用 `fixDetailRowHeight(index)`,确保主表行高随异步内容撑开而不会遮挡。
服务端详情片段与本地回环实测
第三步由服务端接口按 `itemid` 检索记录并输出包含图片与字段明细的 HTML 片段(注:历史教学代码中的 PHP `mysql_real_escape_string`/`mysql_query` 扩展已于 PHP 7.0 移除,现代项目必须改用 PDO 预处理参数绑定并转义输出以防 SQL 注入与 XSS)。本站启动本地 `127.0.0.1` 回环 HTTP 服务配无头 Chromium 实测:初始 3 行均带 `+` 按钮且隐藏空 `.ddv`;点击第 0 行(`EST-10`)展开后按钮切为 `-`,异步加载含 `images/shirt10.gif` 引用与 `Spotted Adult Female` 属性的详情表,`fixDetailRowHeight` 被调用 `2` 次并将详情区高度修正至 `> 60px`;折叠后再二次展开时,因 `cache: false` 服务端对 `EST-10` 的请求计数递增至 `2`。
原压缩包 `jeasyui-datagrid-datagrid21.zip` 未联网下载,已通过本地回环接口与无头浏览器实测覆盖完整异步展开链路。
运行 DataGrid detailview 异步行展开与 fixDetailRowHeight 离线回环实验
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 42: DataGrid Expand Row (detailview)."""
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import threading
from urllib.parse import parse_qs, urlparse
from playwright.sync_api import sync_playwright
ITEMS = [
{"itemid": "EST-10", "productid": "K9-DL-01", "listprice": "18.50", "unitcost": "12.00", "attr1": "Spotted Adult Female", "status": "P"},
{"itemid": "EST-9", "productid": "K9-RT-02", "listprice": "145.49", "unitcost": "100.00", "attr1": "Adult Female", "status": "P"},
{"itemid": "EST-8", "productid": "RP-SN-01", "listprice": "18.50", "unitcost": "12.00", "attr1": "Rattleless", "status": "P"},
]
HTML_PAGE = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>EasyUI DataGrid DetailView Offline Lab</title>
<style>
body { font-family: sans-serif; margin: 16px; font-size: 13px; }
.dg-wrap { width: 500px; border: 1px solid #95b8e7; }
.dg-title { background: #e0ecff; padding: 6px 8px; font-weight: bold; }
table#dg { width: 100%; border-collapse: collapse; }
table#dg th, table#dg td { border: 1px solid #ccc; padding: 4px 6px; }
table#dg th { background: #f4f4f4; }
.expander { width: 20px; height: 20px; cursor: pointer; font-weight: bold; }
tr.detail-row.hidden { display: none; }
.dv-table td { border: 0 !important; padding: 3px 6px !important; }
.dv-label { font-weight: bold; color: #15428b; }
</style>
</head>
<body>
<div class="dg-wrap">
<div class="dg-title">DataGrid - Expand Row</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>Status</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script>
const fixHeightLog = [];
const detailview = {
detailFormatter(index, row) {
return '<div class="ddv" style="padding:5px 0"></div>';
},
fixDetailRowHeight(index) {
const tr = document.querySelector(`tr.detail-row[data-index="${index}"]`);
const ddv = tr.querySelector("div.ddv");
const h = Math.round(ddv.getBoundingClientRect().height);
tr.dataset.fixedHeight = String(h);
fixHeightLog.push({ index, height: h });
}
};
async function initGrid() {
const resp = await fetch("/datagrid8_getdata?sort=itemid&order=desc");
const rows = await resp.json();
const tbody = document.querySelector("#dg tbody");
tbody.innerHTML = "";
rows.forEach((row, index) => {
const tr = document.createElement("tr");
tr.className = "data-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 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="6">${detailview.detailFormatter(index, row)}</td>`;
tbody.append(tr, dtr);
tr.querySelector(".expander").addEventListener("click", async (ev) => {
const btn = ev.currentTarget;
const isExpanded = btn.textContent === "-";
if (isExpanded) {
btn.textContent = "+";
dtr.classList.add("hidden");
return;
}
btn.textContent = "-";
dtr.classList.remove("hidden");
detailview.fixDetailRowHeight(index);
const ddv = dtr.querySelector("div.ddv");
// cache: false -> always reload from server on expand
const htmlResp = await fetch(`/datagrid21_getdetail?itemid=${encodeURIComponent(row.itemid)}&_ts=${Date.now()}`);
ddv.innerHTML = await htmlResp.text();
detailview.fixDetailRowHeight(index);
window.__lastExpanded = { index, itemid: row.itemid };
});
});
window.__gridReady = true;
}
window.lab = { fixHeightLog };
initGrid();
</script>
</body>
</html>
"""
def make_handler(hit_counter):
class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
pass
def do_GET(self):
parsed = urlparse(self.path)
if parsed.path == "/":
body = HTML_PAGE.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write(body)
elif parsed.path == "/datagrid8_getdata":
body = json.dumps(ITEMS).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(body)
elif parsed.path == "/datagrid21_getdetail":
qs = parse_qs(parsed.query)
itemid = qs.get("itemid", [""])[0]
hit_counter[itemid] = hit_counter.get(itemid, 0) + 1
item = next((x for x in ITEMS if x["itemid"] == itemid), ITEMS[0])
serno = item["itemid"].split("-")[1]
svg = f"data:image/svg+xml;utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='60' height='60'%3E%3Crect width='60' height='60' fill='%23dbeafe'/%3E%3C/svg%3E"
frag = f"""<table class="dv-table" border="0" style="width:100%;">
<tr>
<td rowspan="3" style="width:60px"><img data-img="images/shirt{serno}.gif" src="{svg}" style="width:60px;height:60px;margin-right:20px" /></td>
<td class="dv-label">Item ID: </td><td>{item['itemid']}</td>
<td class="dv-label">Product ID:</td><td>{item['productid']}</td>
</tr>
<tr>
<td class="dv-label">List Price: </td><td>{item['listprice']}</td>
<td class="dv-label">Unit Cost:</td><td>{item['unitcost']}</td>
</tr>
<tr>
<td class="dv-label">Attribute: </td><td colspan="3">{item['attr1']}</td>
</tr>
</table>"""
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write(frag.encode("utf-8"))
else:
self.send_response(404)
self.end_headers()
return Handler
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
hits = {}
server = HTTPServer(("127.0.0.1", 0), make_handler(hits))
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.__gridReady === true")
# Case 1: Initial rows have '+' expander and empty hidden .ddv container
res1 = page.evaluate("""() => ({
itemids: Array.from(document.querySelectorAll("tr.data-row")).map(r => r.dataset.itemid),
expanders: Array.from(document.querySelectorAll(".expander")).map(b => b.textContent),
hiddenDetailRows: Array.from(document.querySelectorAll("tr.detail-row")).filter(r => getComputedStyle(r).display === "none").length,
initialDdvEmpty: Array.from(document.querySelectorAll("div.ddv")).every(d => d.innerHTML === "")
})""")
exp1 = {
"itemids": ["EST-10", "EST-9", "EST-8"],
"expanders": ["+", "+", "+"],
"hiddenDetailRows": 3,
"initialDdvEmpty": True,
}
cases.append(dict(name="detailview_initial_expander_and_empty_container", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: Expanding row 0 loads HTML fragment via AJAX and fixes detail row height
page.click('.expander[data-index="0"]')
page.wait_for_selector('tr.detail-row[data-index="0"] table.dv-table')
res2 = page.evaluate("""() => {
const dtr = document.querySelector('tr.detail-row[data-index="0"]');
const img = dtr.querySelector("img");
return {
btnText: document.querySelector('.expander[data-index="0"]').textContent,
detailVisible: getComputedStyle(dtr).display !== "none",
imgRef: img.dataset.img,
hasAttributeText: dtr.textContent.includes("Spotted Adult Female"),
fixedHeightGt60: Number(dtr.dataset.fixedHeight) > 60,
fixCallsForRow0: window.lab.fixHeightLog.filter(x => x.index === 0).length
};
}""")
exp2 = {
"btnText": "-",
"detailVisible": True,
"imgRef": "images/shirt10.gif",
"hasAttributeText": True,
"fixedHeightGt60": True,
"fixCallsForRow0": 2,
}
cases.append(dict(name="detailview_expand_fetches_detail_and_fixes_height", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: Collapse hides row; re-expanding with cache=false re-fetches server endpoint
page.click('.expander[data-index="0"]')
collapsed = page.evaluate("""() => ({
btnText: document.querySelector('.expander[data-index="0"]').textContent,
hidden: getComputedStyle(document.querySelector('tr.detail-row[data-index="0"]')).display === "none"
})""")
page.click('.expander[data-index="0"]')
page.wait_for_function("() => window.lab.fixHeightLog.filter(x => x.index === 0).length === 4")
res3 = {**collapsed, "serverFetchCountForEST10": hits.get("EST-10", 0)}
exp3 = {"btnText": "+", "hidden": True, "serverFetchCountForEST10": 2}
cases.append(dict(name="detailview_collapse_and_nocache_reload", 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()
- 核对初始 '+' 展开器与空 .ddv、展开加载 EST-10 详情表并 2 次调用 fixDetailRowHeight、折叠后二次展开触发 cache:false 再次请求(计数=2)。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:b2f6d2222d25e7ad73c0d4fe044a10e417dc1338156fd38566ea562ddbac6fd0
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:b302933483469beb162e7e7e35e6905ac4d6ea174933778cdbdf2f15d9352d24
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 onExpandRow 中加载远程详情内容时,为什么既要在 panel 的 onLoad 中调用 fixDetailRowHeight,又要在 panel 初始化后立即调用一次?
展开参考解答
立即调用可先为加载提示或初始容器预留高度,而远程 HTML 片段异步返回并撑高 DOM 后,必须在 onLoad 回调中再次调用 fixDetailRowHeight 重新同步冻结区与内容区行高,防止行错位或内容被截断。