jEasyUI 列运算
核对可编辑 DataGrid 中基于 getEditors 与 change 事件的实时列联动运算,以及 onClickRow 切换编辑行并落盘保存的实测表现。
学完这一章,你能够
- 核对可编辑 DataGrid 中基于 getEditors 与 change 事件的实时列联动运算,以及 onClickRow 切换编辑行并落盘保存的实测表现。
构建包含联动运算列的可编辑表格
业务单据录入常需根据单价与数量实时算出小计。通过在 DataGrid 中将 `listprice`(精度 1)、`amount`(精度 0)与运算结果列 `unitcost` 均设为 `numberbox` 编辑器(并配合 `attr1` 文本列与 `status` 复选框列),即可在行编辑状态下建立字段间的动态公式关系,使 `unitcost` 自动等于 `listprice * amount`。
点击切行与编辑器事件绑定实测
交互控制分为两步:首先在 `onClickRow` 回调中比对 `lastIndex` 与当前 `rowIndex`,仅当切换至不同行时依次调用 `endEdit(lastIndex)`、`beginEdit(rowIndex)` 并执行 `setEditing(rowIndex)`;随后在 `setEditing` 内通过 `getEditors(rowIndex)` 按列顺序取出 `priceEditor`、`amountEditor` 与 `costEditor`,为前两者的目标输入框绑定 `change` 事件以重新计算乘积并调用 `numberbox('setValue', cost)` 写入结果列。本站离线 Chromium 实测:点击第 0 行挂载 `['listprice', 'amount', 'unitcost', 'attr1', 'status']` 共 5 个编辑器,重复点击同一行不重复重启,切至第 1 行记录完整事件序 `['begin:0', 'end:0', 'begin:1']`;在编辑态将单价设为 `16.5`、数量改为 `4` 与 `10` 时,`unitcost` 分别实时算出 `66` 与 `165`;输入 `12.5 * 6` 并调用 `endEdit(0)` 后,单元格与行数据同步落盘为 `75`。
参考示例包 `jeasyui-datagrid-datagrid15.zip` 因来源访问限制未下载,上述离线无头浏览器脚本已覆盖切行编辑、change 联动运算及提交保存三个环节。
运行 DataGrid 行内列联动运算与切行提交离线实验
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 36: DataGrid Calculated Column."""
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 Calculated Column Offline Lab</title>
<style>
body { font-family: sans-serif; margin: 16px; font-size: 13px; }
table#tt { width: 600px; border-collapse: collapse; }
table#tt th, table#tt td { border: 1px solid #ccc; padding: 4px 6px; }
table#tt th { background: #e0ecff; }
table#tt tr.editing { background: #fffbe6; }
table#tt input[type="text"] { width: 68px; text-align: right; }
</style>
</head>
<body>
<table id="tt">
<thead>
<tr>
<th>Item ID</th><th>List Price</th><th>Amount</th><th>Unit Cost</th><th>Attribute</th><th>Status</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
const rows = [
{ itemid: "EST-1", listprice: 16.5, amount: 2, unitcost: 33, attr1: "Large", status: "P" },
{ itemid: "EST-10", listprice: 18.5, amount: 3, unitcost: 55.5, attr1: "Spotted Adult Female", status: "P" },
{ itemid: "EST-11", listprice: 12.5, amount: 4, unitcost: 50, attr1: "Venomless", status: "" }
];
const fields = [
{ field: "itemid", editor: null },
{ field: "listprice", editor: { type: "numberbox", precision: 1 } },
{ field: "amount", editor: { type: "numberbox", precision: 0 } },
{ field: "unitcost", editor: { type: "numberbox", precision: 2 } },
{ field: "attr1", editor: { type: "text" } },
{ field: "status", editor: { type: "checkbox", on: "P", off: "" } }
];
let lastIndex = undefined;
const activeEditors = new Map();
const eventLog = [];
function render() {
const tbody = document.querySelector("#tt tbody");
tbody.innerHTML = "";
rows.forEach((row, idx) => {
const tr = document.createElement("tr");
tr.dataset.index = String(idx);
fields.forEach(col => {
const td = document.createElement("td");
td.dataset.field = col.field;
td.textContent = String(row[col.field]);
tr.appendChild(td);
});
tr.addEventListener("click", () => onClickRow(idx));
tbody.appendChild(tr);
});
}
function beginEdit(idx) {
eventLog.push("begin:" + idx);
const tr = document.querySelector(`#tt tbody tr[data-index="${idx}"]`);
tr.classList.add("editing");
const list = [];
fields.forEach(col => {
if (!col.editor) return;
const td = tr.querySelector(`td[data-field="${col.field}"]`);
td.innerHTML = "";
const inp = document.createElement("input");
if (col.editor.type === "checkbox") {
inp.type = "checkbox";
inp.checked = (rows[idx][col.field] === col.editor.on);
} else {
inp.type = "text";
inp.value = String(rows[idx][col.field]);
}
td.appendChild(inp);
list.push({ field: col.field, type: col.editor.type, options: col.editor, target: inp });
});
activeEditors.set(idx, list);
}
function endEdit(idx) {
if (idx === undefined || !activeEditors.has(idx)) return;
eventLog.push("end:" + idx);
const list = activeEditors.get(idx);
list.forEach(ed => {
if (ed.type === "checkbox") {
rows[idx][ed.field] = ed.target.checked ? ed.options.on : ed.options.off;
} else if (ed.type === "numberbox") {
const num = parseFloat(ed.target.value);
rows[idx][ed.field] = Number.isNaN(num) ? 0 : Number(num.toFixed(ed.options.precision));
} else {
rows[idx][ed.field] = ed.target.value;
}
});
activeEditors.delete(idx);
render();
}
function getEditors(idx) {
return activeEditors.get(idx) || [];
}
function setEditing(rowIndex) {
const editors = getEditors(rowIndex);
const priceEditor = editors[0];
const amountEditor = editors[1];
const costEditor = editors[2];
function calculate() {
const cost = parseFloat(priceEditor.target.value) * parseFloat(amountEditor.target.value);
costEditor.target.value = Number.isNaN(cost) ? "" : String(Number(cost.toFixed(2)));
}
priceEditor.target.addEventListener("change", calculate);
amountEditor.target.addEventListener("change", calculate);
}
function onClickRow(rowIndex) {
if (lastIndex !== rowIndex) {
endEdit(lastIndex);
beginEdit(rowIndex);
setEditing(rowIndex);
}
lastIndex = rowIndex;
}
render();
window.lab = { rows, getEditors, endEdit, getState: () => ({ lastIndex, eventLog: [...eventLog] }) };
</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: onClickRow starts editing once per row and switches cleanly on another row click
page.click('#tt tbody tr[data-index="0"]')
ed_fields = page.evaluate("() => window.lab.getEditors(0).map(e => e.field)")
page.click('#tt tbody tr[data-index="0"] td[data-field="itemid"]')
page.click('#tt tbody tr[data-index="1"] td[data-field="itemid"]')
st = page.evaluate("() => window.lab.getState()")
res1 = {"editorFields": ed_fields, "lastIndex": st["lastIndex"], "eventLog": st["eventLog"]}
exp1 = {
"editorFields": ["listprice", "amount", "unitcost", "attr1", "status"],
"lastIndex": 1,
"eventLog": ["begin:0", "end:0", "begin:1"],
}
cases.append(dict(name="onclickrow_switch_editing_row", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: Change binding between listprice, amount and computed unitcost editor
page.click('#tt tbody tr[data-index="0"] td[data-field="itemid"]')
price_loc = page.locator('#tt tbody tr[data-index="0"] td[data-field="listprice"] input')
amt_loc = page.locator('#tt tbody tr[data-index="0"] td[data-field="amount"] input')
cost_loc = page.locator('#tt tbody tr[data-index="0"] td[data-field="unitcost"] input')
price_loc.fill("16.5")
price_loc.dispatch_event("change")
amt_loc.fill("4")
amt_loc.dispatch_event("change")
cost_after_4 = cost_loc.input_value()
amt_loc.fill("10")
amt_loc.dispatch_event("change")
cost_after_10 = cost_loc.input_value()
res2 = {"costAfter4": cost_after_4, "costAfter10": cost_after_10}
exp2 = {"costAfter4": "66", "costAfter10": "165"}
cases.append(dict(name="calculated_column_change_binding", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: endEdit commits calculated value into row model and rendered cells
price_loc.fill("12.5")
price_loc.dispatch_event("change")
amt_loc.fill("6")
amt_loc.dispatch_event("change")
page.evaluate("() => window.lab.endEdit(0)")
res3 = page.evaluate("""() => ({
row0: window.lab.rows[0],
renderedCells: Array.from(document.querySelectorAll('#tt tbody tr[data-index="0"] td')).map(td => td.textContent)
})""")
exp3 = {
"row0": {"itemid": "EST-1", "listprice": 12.5, "amount": 6, "unitcost": 75, "attr1": "Large", "status": "P"},
"renderedCells": ["EST-1", "12.5", "6", "75", "Large", "P"],
}
cases.append(dict(name="end_edit_persists_calculated_value", expected=exp3, actual=res3, passed=(res3 == exp3)))
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对 onClickRow 切行事件序、16.5*4=66 与 16.5*10=165 实时重算,以及 endEdit 提交 12.5*6=75 落盘结果。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:a72eccc8c1e3bd98de0efa53aa0497d4f0b7ee738825e6e9092970725509015e
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:30cdeca2e809808888df548a525669f12f8cf1890f212d5dfbd08c772f034970
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么在 onClickRow 中需要维护 lastIndex 并在 beginEdit 之后调用 setEditing?
展开参考解答
维护 lastIndex 可以避免重复点击同一行导致编辑器重建,并确保切到新行前先用 endEdit 保存上一行改动;而 getEditors 只有在 beginEdit 创建编辑器 DOM 之后才能获取到目标输入元素来绑定 change 事件。