蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 DataGrid 行内列联动运算与切行提交离线实验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-datagrid-datagrid15.py
explore-datagrid-datagrid15.py208 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/jeasyui-datagrid-datagrid15-lab/explore-datagrid-datagrid15.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-datagrid-datagrid15.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:jQuery EasyUI

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a971.zip

下载课程关联工程包:jQuery EasyUI

课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习