jEasyUI 动态改变列
核对运行期重复调用 datagrid({columns: [...]}) 动态切换列结构时自动保留 url、width、height、singleSelect 等既有配置的离线 Chromium 实测。
学完这一章,你能够
- 核对运行期重复调用 datagrid({columns: [...]}) 动态切换列结构时自动保留 url、width、height、singleSelect 等既有配置的离线 Chromium 实测。
初始化基础四列数据网格
当不同角色或视图模式需要展示不同字段集合时,DataGrid 允许在运行期重新调用 `datagrid` 方法并传入新的 `columns` 二维数组动态重构列结构。初始阶段先在 HTML 表格中声明 `width:550px`、`height:250px`、`url="data/datagrid_data.json"` 与 `singleSelect="true"`,再通过 JS 配置 4 列(`itemid`、`productid`、`attr1` 宽 `200`、`status` 宽 `80`)。本站 Chromium 实测初始渲染为 4 列 3 行,首行展示 `['EST-1', 'FI-SW-01', 'Large', 'P']`。
增量覆写 columns 并保留既有属性
需要切换至更详细的 6 列视图时,只需再次调用 `$('#tt').datagrid({ columns: [[...]] })`,插入右对齐的 `listprice` 与 `unitcost` 两列并将 `attr1`/`status` 宽度分别调为 `100` 和 `60`。此前已设定的 `url`、`width`、`height` 与 `singleSelect` 等配置会自动沿用,无需重复传入。本站 Chromium 实测切换后表头扩展为 6 列、`listprice`/`unitcost` 呈现右对齐、原 4 项基础属性完整保留;再切回 4 列时底层 3 条记录与 `itemid` 顺序完全不受破坏。
参考示例包 `jeasyui-datagrid-datagrid6.zip` 未发起外网下载并已登记于附件清单;运行本地离线实验脚本可完整核验 4 列 ↔ 6 列动态切换及配置继承行为。
运行 DataGrid 动态切换四列/六列及保留既有属性的离线 Chromium 实验
展开查看收起
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 27: Dynamic Columns."""
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 Dynamic Columns Offline Lab</title>
<style>
body { font-family: sans-serif; margin: 12px; }
.dg-panel { 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; font-size: 12px; }
th, td { border: 1px solid #ddd; padding: 4px 6px; }
th { background: #efefef; }
</style>
</head>
<body>
<div class="dg-panel" id="tt-wrap" style="width:550px;">
<div class="dg-title" id="tt-title"></div>
<table id="tt" title="Dynamic Columns" class="easyui-datagrid" style="width:550px;height:250px"
url="data/datagrid_data.json" singleSelect="true" iconCls="icon-save">
<thead></thead>
<tbody></tbody>
</table>
</div>
<script>
const DATASET = [
{ 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 Adult Female", status: "P" },
{ itemid: "EST-11", productid: "RP-SN-01", listprice: 28.5, unitcost: 12.0, attr1: "Venomless", status: "P" },
];
const tbl = document.getElementById('tt');
const dgState = {
options: {
url: tbl.getAttribute('url'),
width: 550,
height: 250,
singleSelect: tbl.getAttribute('singleSelect') === 'true',
title: tbl.getAttribute('title'),
iconCls: tbl.getAttribute('iconCls'),
columns: [],
},
rows: DATASET,
selectedIdx: null,
};
document.getElementById('tt-title').textContent = dgState.options.title;
window.datagrid = function(newOpts) {
Object.assign(dgState.options, newOpts);
dgState.selectedIdx = null;
const cols = dgState.options.columns[0] || [];
const thead = tbl.querySelector('thead');
const tbody = tbl.querySelector('tbody');
thead.innerHTML = '<tr>' + cols.map(c => `<th data-field="${c.field}" style="width:${c.width}px">${c.title}</th>`).join('') + '</tr>';
tbody.innerHTML = dgState.rows.map((r, ri) =>
`<tr data-idx="${ri}">` + cols.map(c => {
const alignStyle = c.align ? `text-align:${c.align};` : '';
return `<td data-field="${c.field}" style="${alignStyle}">${r[c.field]}</td>`;
}).join('') + '</tr>'
).join('');
};
window.getGridSnapshot = function() {
const cols = dgState.options.columns[0] || [];
const firstRowCells = Array.from(tbl.querySelectorAll('tbody tr:first-child td')).map(td => ({
field: td.dataset.field,
text: td.textContent,
align: td.style.textAlign || 'left',
}));
return {
columnFields: cols.map(c => c.field),
columnWidths: cols.map(c => c.width),
preservedOptions: {
url: dgState.options.url,
width: dgState.options.width,
height: dgState.options.height,
singleSelect: dgState.options.singleSelect,
},
rowCount: tbl.querySelectorAll('tbody tr').length,
firstRowCells,
selectedIdx: dgState.selectedIdx,
};
};
// Initial 4-column definition
window.datagrid({
columns: [[
{ field: 'itemid', title: 'Item ID', width: 80 },
{ field: 'productid', title: 'Product ID', width: 80 },
{ field: 'attr1', title: 'Attribute', width: 200 },
{ field: 'status', title: 'Status', width: 80 },
]]
});
</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": 700, "height": 420})
page.set_content(HTML_DOC)
# Case 1: Initial 4-column render inheriting declarative options
res1 = page.evaluate("() => window.getGridSnapshot()")
exp1 = {
"columnFields": ["itemid", "productid", "attr1", "status"],
"columnWidths": [80, 80, 200, 80],
"preservedOptions": {"url": "data/datagrid_data.json", "width": 550, "height": 250, "singleSelect": True},
"rowCount": 3,
"firstRowCells": [
{"field": "itemid", "text": "EST-1", "align": "left"},
{"field": "productid", "text": "FI-SW-01", "align": "left"},
{"field": "attr1", "text": "Large", "align": "left"},
{"field": "status", "text": "P", "align": "left"},
],
"selectedIdx": None,
}
cases.append(dict(name="initial_four_column_render", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: Re-invoke datagrid with 6 columns only -> preserves url/width/height/singleSelect
page.evaluate("""() => window.datagrid({
columns: [[
{ field: 'itemid', title: 'Item ID', width: 80 },
{ field: 'productid', title: 'Product ID', width: 80 },
{ field: 'listprice', title: 'List Price', width: 80, align: 'right' },
{ field: 'unitcost', title: 'Unit Cost', width: 80, align: 'right' },
{ field: 'attr1', title: 'Attribute', width: 100 },
{ field: 'status', title: 'Status', width: 60 },
]]
})""")
res2 = page.evaluate("() => window.getGridSnapshot()")
exp2 = {
"columnFields": ["itemid", "productid", "listprice", "unitcost", "attr1", "status"],
"columnWidths": [80, 80, 80, 80, 100, 60],
"preservedOptions": {"url": "data/datagrid_data.json", "width": 550, "height": 250, "singleSelect": True},
"rowCount": 3,
"firstRowCells": [
{"field": "itemid", "text": "EST-1", "align": "left"},
{"field": "productid", "text": "FI-SW-01", "align": "left"},
{"field": "listprice", "text": "16.5", "align": "right"},
{"field": "unitcost", "text": "10", "align": "right"},
{"field": "attr1", "text": "Large", "align": "left"},
{"field": "status", "text": "P", "align": "left"},
],
"selectedIdx": None,
}
cases.append(dict(name="dynamic_reinit_six_columns_preserves_options", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: Switch back to 4 columns without losing underlying records
page.evaluate("""() => window.datagrid({
columns: [[
{ field: 'itemid', title: 'Item ID', width: 80 },
{ field: 'productid', title: 'Product ID', width: 80 },
{ field: 'attr1', title: 'Attribute', width: 200 },
{ field: 'status', title: 'Status', width: 80 },
]]
})""")
res3 = page.evaluate("""() => ({
colCount: document.querySelectorAll('#tt thead th').length,
itemids: Array.from(document.querySelectorAll('#tt tbody td[data-field="itemid"]')).map(td => td.textContent),
rowCount: document.querySelectorAll('#tt tbody tr').length,
})""")
exp3 = {"colCount": 4, "itemids": ["EST-1", "EST-10", "EST-11"], "rowCount": 3}
cases.append(dict(name="switch_back_and_data_integrity", expected=exp3, actual=res3, passed=(res3 == exp3)))
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`showColumn`/`hideColumn` 仅切换已定义列的显隐,不触发重建和重新请求数据;重新传入 `columns` 可彻底替换列顺序、列宽、对齐方式与格式化器,同时保留未修改的其他网格选项。