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

jEasyUI 格式化列

核对 DataGrid 列 formatter 回调的三参数签名 (value, row, index)、价格小于 20 标红加括号的条件渲染,以及不篡改原始数值字段的离线 Chromium 实测。

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

学完这一章,你能够

列格式化器 formatter 的参数签名与作用

为了按业务阈值高亮或定制单元格展示形式,可为 DataGrid 列指定 `formatter` 函数。组件渲染每个单元格时都会向该函数传入 3 个参数:`value` 表示当前列对应的原始字段值,`row` 表示当前整行记录对象,`index` 表示从 `0` 开始的行下标。

绑定 formatPrice 与边界值离线实测

在表头 `<th field="listprice" width="80" align="right" formatter="formatPrice">` 中声明格式化函数名,并在脚本中实现 `formatPrice(val, row)`:当 `val < 20` 时返回 `<span style="color:red;">(` + `val` + `)</span>`,否则原样返回 `val`。本站 Chromium 对 `[16.5, 18.5, 20.0, 38.5, 19.99]` 五行价格实测:`16.5`、`18.5`、`19.99` 均渲染红色括号文本(计算颜色 `rgb(255, 0, 0)`),临界值 `20` 与 `38.5` 走 `else` 分支保持普通文本;同时核验回调完整接收了全部 5 组 `(val, row, index)`,原始记录中的 `row.listprice` 仍为 `number` 类型未被 HTML 污染,且全部单元格维持 `text-align: right`。

参考压缩包 `jeasyui-datagrid-datagrid7.zip` 未发起外网下载并已登记于附件清单;通过本地离线 Chromium 实验脚本可直接核验条件标红、边界值 `20` 行为与原始数据隔离。

运行 DataGrid 列 formatter 条件标红与边界值隔离的离线 Chromium 实验

python · 阅读源码
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 28: Formatting 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 Formatting Columns Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 12px; }
  .dg-panel { width: 550px; border: 1px solid #95b8e7; }
  .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">
  <div class="dg-title">Formatting Columns</div>
  <table id="tt">
    <thead>
      <tr>
        <th field="itemid" width="80">Item ID</th>
        <th field="productid" width="80">Product ID</th>
        <th field="listprice" width="80" align="right" formatter="formatPrice">List Price</th>
        <th field="unitcost" width="80" align="right">Unit Cost</th>
        <th field="attr1" width="100">Attribute</th>
        <th field="status" width="60" align="center">Status</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>
<script>
const ROWS = [
  { 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", status: "P" },
  { itemid: "EST-20", productid: "K9-BD-01", listprice: 20.0, unitcost: 12.0, attr1: "Boundary", status: "P" },
  { itemid: "EST-11", productid: "RP-SN-01", listprice: 38.5, unitcost: 12.0, attr1: "Venomless", status: "P" },
  { itemid: "EST-12", productid: "RP-LI-02", listprice: 19.99, unitcost: 12.0, attr1: "Green", status: "P" },
];
window.formatterCalls = [];

function formatPrice(val, row, index) {
  window.formatterCalls.push({ val, itemid: row.itemid, index });
  if (val < 20) {
    return '<span style="color:red;">(' + val + ')</span>';
  } else {
    return val;
  }
}

const ths = Array.from(document.querySelectorAll('#tt thead th'));
const tbody = document.querySelector('#tt tbody');
ROWS.forEach((row, index) => {
  const tr = document.createElement('tr');
  ths.forEach(th => {
    const field = th.getAttribute('field');
    const align = th.getAttribute('align');
    const fmtName = th.getAttribute('formatter');
    const td = document.createElement('td');
    td.dataset.field = field;
    if (align) td.style.textAlign = align;
    const raw = row[field];
    if (fmtName && typeof window[fmtName] === 'function') {
      td.innerHTML = String(window[fmtName](raw, row, index));
    } else {
      td.textContent = String(raw);
    }
    tr.appendChild(td);
  });
  tbody.appendChild(tr);
});

window.rawRows = ROWS;
</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": 680, "height": 420})
        page.set_content(HTML_DOC)

        # Case 1: Prices < 20 render red parenthesized span; >= 20 render plain text
        res1 = page.evaluate("""() => Array.from(document.querySelectorAll('#tt tbody td[data-field="listprice"]')).map(td => {
            const span = td.querySelector('span');
            return {
                text: td.textContent.trim(),
                hasRedSpan: Boolean(span),
                color: span ? getComputedStyle(span).color : 'default',
            };
        })""")
        exp1 = [
            {"text": "(16.5)", "hasRedSpan": True, "color": "rgb(255, 0, 0)"},
            {"text": "(18.5)", "hasRedSpan": True, "color": "rgb(255, 0, 0)"},
            {"text": "20", "hasRedSpan": False, "color": "default"},
            {"text": "38.5", "hasRedSpan": False, "color": "default"},
            {"text": "(19.99)", "hasRedSpan": True, "color": "rgb(255, 0, 0)"},
        ]
        cases.append(dict(name="formatter_conditional_red_under_20", expected=exp1, actual=res1, passed=(res1 == exp1)))

        # Case 2: Formatter receives (value, row, index) and leaves raw row numeric values unmutated
        res2 = page.evaluate("""() => ({
            calls: window.formatterCalls,
            rawTypes: window.rawRows.map(r => typeof r.listprice),
            rawValues: window.rawRows.map(r => r.listprice),
        })""")
        exp2 = {
            "calls": [
                {"val": 16.5, "itemid": "EST-1", "index": 0},
                {"val": 18.5, "itemid": "EST-10", "index": 1},
                {"val": 20, "itemid": "EST-20", "index": 2},
                {"val": 38.5, "itemid": "EST-11", "index": 3},
                {"val": 19.99, "itemid": "EST-12", "index": 4},
            ],
            "rawTypes": ["number", "number", "number", "number", "number"],
            "rawValues": [16.5, 18.5, 20, 38.5, 19.99],
        }
        cases.append(dict(name="formatter_receives_value_row_index", expected=exp2, actual=res2, passed=(res2 == exp2)))

        # Case 3: Exact boundary 20.0 stays unformatted and right alignment is preserved
        res3 = page.evaluate("""() => {
            const cells = Array.from(document.querySelectorAll('#tt tbody td[data-field="listprice"]'));
            return {
                boundaryInnerHTML: cells[2].innerHTML,
                allRightAligned: cells.every(td => getComputedStyle(td).textAlign === 'right'),
            };
        }""")
        exp3 = {"boundaryInnerHTML": "20", "allRightAligned": True}
        cases.append(dict(name="boundary_value_exact_20_and_alignment", expected=exp3, actual=res3, passed=(res3 == exp3)))

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


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对价格 < 20 渲染 rgb(255, 0, 0) 括号文本、边界值 20 原样输出、回调收到完整 (value, row, index) 且原始数值类型保持 number。
运行 DataGrid 列 formatter 条件标红与边界值隔离的离线 Chromium 实验

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

当前源码 SHA256:7fa6b15cf2ffc08c36f1b664ca813419324316e940f19fdcf86de33a32342981

下载本站示例源码

本地运行

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

下载jEasyUI 格式化列实验

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

ZIP SHA256:d1881a7b01ec08e1b95153ec6dab608b77ef56bd401cd6bace0d023ab35678da

常见错误与边界

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

练习与解答

`formatter` 返回带 HTML 标签的字符串会影响该行原始数据中的字段值吗?若字段内容来自用户输入,编写 `formatter` 时有何安全注意事项?

展开参考解答

`formatter` 仅控制单元格的展示 HTML,不会修改底层行对象的原始数值或字符串;但因返回值通常作为 HTML 片段插入 DOM,若直接拼接不可信用户输入须先做 HTML 转义以防 XSS 注入。

规范与官方依据