蓝色天空网mbsky.com · 知识 · 实践 · 创造jQuery EasyUI · 本地阅读预览
教程 / 前端开发 / jQuery EasyUI

jEasyUI 扩展编辑器

核对 $.fn.datagrid.defaults.editors 扩展接口、numberspinner 编辑器五项生命周期方法,以及在 DataGrid 列标记中的绑定与行内编辑实测。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

扩展 $.fn.datagrid.defaults.editors 接口

jQuery EasyUI 数据网格内置了 text、numberbox、checkbox 等常用行内编辑器,所有编辑器均注册在 `$.fn.datagrid.defaults.editors` 对象上。若业务需要数字微调框等自定义控件,只需通过 `$.extend` 向该对象挂载同名定义(例如 `numberspinner`),并实现 `init`、`destroy`、`getValue`、`setValue`、`resize` 五个生命周期方法即可融入行编辑流程。本站离线无头浏览器实测确认:独立挂载 `numberspinner` 后,`setValue('25.5')` 与 `getValue()` 精确一致,`resize(110)` 将控件容器宽度设为 `110px`,调用 `destroy` 后微调框 DOM 节点数由 `1` 归 `0`。

在 HTML 列定义中绑定 numberspinner 编辑器

完成注册后,可在 `<table>` 列头的 `editor` 属性中直接以字符串 `editor="numberspinner"` 绑定到 `unitcost` 字段,与同表的 `listprice`(精度为 1 的 `numberbox`)、`attr1`(`text`)及 `status`(`on:'P'`/`off:''` 的 `checkbox`)协同工作。本站离线 Chromium 实测对第 0 行进入编辑态:连续点击两次微调加号将 `unitcost` 从 `10` 增至 `12`,将 `listprice` 改为 `18.56` 自动按精度格式化为 `18.6`,取消勾选 `status` 得到空串,提交保存后单元格同步更新;另测第 1 行编辑改为 `99` 后取消,触发 `destroy` 卸载微调框且原值 `12` 保持不变。

原参考页面提供的 `jeasyui-datagrid-datagrid23.zip` 压缩包未联网拉取,本站通过上述独立离线无头浏览器实验完整复现编辑器注册、行内微调与销毁回滚逻辑。

运行 DataGrid 扩展 numberspinner 编辑器生命周期与行内微调离线实验

python · 阅读源码
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 35: Extend DataGrid Editors (numberspinner)."""
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 Extend Editor Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 16px; font-size: 13px; }
  .datagrid-wrap { width: 600px; border: 1px solid #95b8e7; }
  .datagrid-title { background: #e0ecff; padding: 6px 8px; font-weight: bold; border-bottom: 1px solid #95b8e7; }
  table.dg { width: 100%; border-collapse: collapse; table-layout: fixed; }
  table.dg th, table.dg td { border: 1px solid #ccc; padding: 4px 6px; overflow: hidden; }
  table.dg th { background: #f4f4f4; }
  .spinner-wrap { display: inline-flex; align-items: center; border: 1px solid #95b8e7; box-sizing: border-box; }
  .spinner-wrap input { border: 0; width: calc(100% - 20px); outline: none; text-align: right; font-size: 12px; }
  .spinner-btns { display: flex; flex-direction: column; width: 18px; }
  .spinner-btns button { font-size: 9px; line-height: 9px; padding: 0; border: 0; border-left: 1px solid #ccc; cursor: pointer; background: #eee; }
</style>
</head>
<body>
<div class="datagrid-wrap">
  <div class="datagrid-title">Editable DataGrid</div>
  <table id="tt" class="dg" data-id-field="itemid">
    <thead>
      <tr>
        <th data-field="itemid" style="width:60px">Item ID</th>
        <th data-field="listprice" style="width:80px;text-align:right">List Price</th>
        <th data-field="unitcost" style="width:80px;text-align:right">Unit Cost</th>
        <th data-field="attr1" style="width:180px">Attribute</th>
        <th data-field="status" style="width:60px;text-align:center">Status</th>
        <th data-field="action" style="width:80px;text-align:center">Action</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>
<div id="unit-sandbox" style="margin-top:12px;"></div>

<script>
const lifecycleLog = [];

const EasyUI = {
  fn: {
    datagrid: {
      defaults: {
        editors: {
          text: {
            init(container) {
              const inp = document.createElement("input");
              inp.type = "text";
              inp.className = "dg-ed-text";
              container.appendChild(inp);
              return inp;
            },
            destroy(target) { target.remove(); },
            getValue(target) { return target.value; },
            setValue(target, value) { target.value = value ?? ""; },
            resize(target, width) { target.style.width = width + "px"; }
          },
          numberbox: {
            init(container, options = {}) {
              const inp = document.createElement("input");
              inp.type = "text";
              inp.className = "dg-ed-numberbox";
              inp._precision = options.precision ?? 0;
              container.appendChild(inp);
              return inp;
            },
            destroy(target) { target.remove(); },
            getValue(target) {
              const n = parseFloat(target.value);
              return Number.isNaN(n) ? "" : n.toFixed(target._precision);
            },
            setValue(target, value) {
              const n = parseFloat(value);
              target.value = Number.isNaN(n) ? "" : n.toFixed(target._precision);
            },
            resize(target, width) { target.style.width = width + "px"; }
          },
          checkbox: {
            init(container, options = { on: "P", off: "" }) {
              const inp = document.createElement("input");
              inp.type = "checkbox";
              inp.className = "dg-ed-checkbox";
              inp._opts = options;
              container.appendChild(inp);
              return inp;
            },
            destroy(target) { target.remove(); },
            getValue(target) { return target.checked ? target._opts.on : target._opts.off; },
            setValue(target, value) { target.checked = (value === target._opts.on); },
            resize() {}
          }
        }
      }
    }
  }
};

// Mirror $.extend($.fn.datagrid.defaults.editors, { numberspinner: ... })
Object.assign(EasyUI.fn.datagrid.defaults.editors, {
  numberspinner: {
    init(container, options = {}) {
      lifecycleLog.push("numberspinner:init");
      const wrap = document.createElement("span");
      wrap.className = "spinner-wrap";
      const input = document.createElement("input");
      input.type = "text";
      input.className = "dg-ed-numberspinner";
      const btns = document.createElement("span");
      btns.className = "spinner-btns";
      const up = document.createElement("button");
      up.type = "button";
      up.className = "spin-up";
      up.textContent = "+";
      const down = document.createElement("button");
      down.type = "button";
      down.className = "spin-down";
      down.textContent = "-";
      const inc = options.increment ?? 1;
      up.addEventListener("click", () => {
        const cur = parseFloat(input.value) || 0;
        input.value = String(cur + inc);
      });
      down.addEventListener("click", () => {
        const cur = parseFloat(input.value) || 0;
        input.value = String(cur - inc);
      });
      btns.append(up, down);
      wrap.append(input, btns);
      container.appendChild(wrap);
      input._wrap = wrap;
      return input;
    },
    destroy(target) {
      lifecycleLog.push("numberspinner:destroy");
      if (target._wrap) target._wrap.remove();
    },
    getValue(target) {
      return target.value;
    },
    setValue(target, value) {
      target.value = value == null ? "" : String(value);
    },
    resize(target, width) {
      if (target._wrap) target._wrap.style.width = width + "px";
    }
  }
});

const columns = [
  { field: "itemid", align: "left", editor: null },
  { field: "listprice", align: "right", editor: { type: "numberbox", options: { precision: 1 } } },
  { field: "unitcost", align: "right", editor: "numberspinner" },
  { field: "attr1", align: "left", editor: "text" },
  { field: "status", align: "center", editor: { type: "checkbox", options: { on: "P", off: "" } } },
  { field: "action", align: "center", editor: null }
];

const rows = [
  { itemid: "EST-1", listprice: "16.5", unitcost: "10", attr1: "Large", status: "P" },
  { itemid: "EST-10", listprice: "18.5", unitcost: "12", attr1: "Spotted Adult Female", status: "P" }
];

const editingMap = new Map();

function renderGrid() {
  const tbody = document.querySelector("#tt tbody");
  tbody.innerHTML = "";
  rows.forEach((row, idx) => {
    const tr = document.createElement("tr");
    tr.dataset.index = String(idx);
    columns.forEach(col => {
      const td = document.createElement("td");
      td.dataset.field = col.field;
      td.style.textAlign = col.align;
      if (col.field === "action") {
        td.textContent = editingMap.has(idx) ? "Save | Cancel" : "Edit";
      } else {
        td.textContent = row[col.field];
      }
      tr.appendChild(td);
    });
    tbody.appendChild(tr);
  });
}

function resolveEditor(spec) {
  if (!spec) return null;
  if (typeof spec === "string") return { type: spec, options: {} };
  return { type: spec.type, options: spec.options || {} };
}

function beginEdit(idx) {
  if (editingMap.has(idx)) return;
  const tr = document.querySelector(`#tt tbody tr[data-index="${idx}"]`);
  const active = [];
  columns.forEach(col => {
    const spec = resolveEditor(col.editor);
    if (!spec) return;
    const def = EasyUI.fn.datagrid.defaults.editors[spec.type];
    const td = tr.querySelector(`td[data-field="${col.field}"]`);
    td.innerHTML = "";
    const target = def.init(td, spec.options);
    def.setValue(target, rows[idx][col.field]);
    def.resize(target, 74);
    active.push({ field: col.field, def, target });
  });
  editingMap.set(idx, active);
  tr.querySelector('td[data-field="action"]').textContent = "Save | Cancel";
}

function endEdit(idx) {
  const active = editingMap.get(idx);
  if (!active) return;
  active.forEach(({ field, def, target }) => {
    rows[idx][field] = def.getValue(target);
    def.destroy(target);
  });
  editingMap.delete(idx);
  renderGrid();
}

function cancelEdit(idx) {
  const active = editingMap.get(idx);
  if (!active) return;
  active.forEach(({ def, target }) => {
    def.destroy(target);
  });
  editingMap.delete(idx);
  renderGrid();
}

renderGrid();
window.lab = { EasyUI, rows, beginEdit, endEdit, cancelEdit, lifecycleLog };
</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: Standalone numberspinner editor contract
        res1 = page.evaluate("""() => {
            const box = document.getElementById("unit-sandbox");
            const ed = window.lab.EasyUI.fn.datagrid.defaults.editors.numberspinner;
            const target = ed.init(box, { increment: 2 });
            ed.setValue(target, "25.5");
            ed.resize(target, 110);
            const val = ed.getValue(target);
            const width = target._wrap.style.width;
            const mountedBeforeDestroy = box.querySelectorAll(".spinner-wrap").length;
            ed.destroy(target);
            const mountedAfterDestroy = box.querySelectorAll(".spinner-wrap").length;
            return {
                methods: Object.keys(ed).sort(),
                value: val,
                width,
                mountedBeforeDestroy,
                mountedAfterDestroy
            };
        }""")
        exp1 = {
            "methods": ["destroy", "getValue", "init", "resize", "setValue"],
            "value": "25.5",
            "width": "110px",
            "mountedBeforeDestroy": 1,
            "mountedAfterDestroy": 0,
        }
        cases.append(dict(name="extend_numberspinner_editor_contract", expected=exp1, actual=res1, passed=(res1 == exp1)))

        # Case 2: DataGrid inline edit using extended numberspinner on unitcost + numberbox/checkbox
        page.evaluate("() => window.lab.beginEdit(0)")
        page.click('#tt tbody tr[data-index="0"] td[data-field="unitcost"] .spin-up')
        page.click('#tt tbody tr[data-index="0"] td[data-field="unitcost"] .spin-up')
        page.fill('#tt tbody tr[data-index="0"] td[data-field="listprice"] input', "18.56")
        page.uncheck('#tt tbody tr[data-index="0"] td[data-field="status"] input')
        page.evaluate("() => window.lab.endEdit(0)")
        res2 = page.evaluate("""() => ({
            row0: window.lab.rows[0],
            cellUnitCost: document.querySelector('#tt tbody tr[data-index="0"] td[data-field="unitcost"]').textContent,
            cellListPrice: document.querySelector('#tt tbody tr[data-index="0"] td[data-field="listprice"]').textContent,
            cellStatus: document.querySelector('#tt tbody tr[data-index="0"] td[data-field="status"]').textContent
        })""")
        exp2 = {
            "row0": {"itemid": "EST-1", "listprice": "18.6", "unitcost": "12", "attr1": "Large", "status": ""},
            "cellUnitCost": "12",
            "cellListPrice": "18.6",
            "cellStatus": "",
        }
        cases.append(dict(name="datagrid_inline_edit_with_numberspinner", expected=exp2, actual=res2, passed=(res2 == exp2)))

        # Case 3: Cancel edit triggers destroy and preserves original unitcost
        page.evaluate("() => window.lab.beginEdit(1)")
        page.fill('#tt tbody tr[data-index="1"] td[data-field="unitcost"] input', "99")
        in_edit_count = page.locator('#tt tbody tr[data-index="1"] .spinner-wrap').count()
        page.evaluate("() => window.lab.cancelEdit(1)")
        res3 = page.evaluate("""(inEditCount) => ({
            inEditCount,
            afterCancelSpinnerCount: document.querySelectorAll('#tt tbody tr[data-index="1"] .spinner-wrap').length,
            preservedUnitCost: window.lab.rows[1].unitcost,
            destroyCount: window.lab.lifecycleLog.filter(x => x === "numberspinner:destroy").length
        })""", in_edit_count)
        exp3 = {
            "inEditCount": 1,
            "afterCancelSpinnerCount": 0,
            "preservedUnitCost": "12",
            "destroyCount": 3,
        }
        cases.append(dict(name="cancel_and_destroy_editor_lifecycle", expected=exp3, actual=res3, passed=(res3 == exp3)))

        browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对五项编辑器接口(init/destroy/getValue/setValue/resize)、110px 宽度调整、微调增至 12 与取消编辑回滚保值 12。
运行 DataGrid 扩展 numberspinner 编辑器生命周期与行内微调离线实验

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

当前源码 SHA256:0034a684dc6bed6dc5ae48d2a3ca1ebd576d4cc4161f5aedb12ff39b0b12c122

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载jEasyUI 扩展编辑器实验

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

ZIP SHA256:28bbb2d816fac30fbe952398bb10b746df0f737d4d2943da18928d733962cc9d

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

向 $.fn.datagrid.defaults.editors 扩展新编辑器时,通常需要实现哪五个核心方法?

展开参考解答

需要实现 init(创建并挂载控件)、destroy(销毁控件释放 DOM)、getValue(读取当前值)、setValue(写入初始值)以及 resize(同步调整控件宽度)。

规范与官方依据