jEasyUI 条件设置行背景颜色
核对 DataGrid 的 rowStyler(index, row) 条件样式回调函数,实测严格大于阈值(listprice > 50)的计算样式、对象返回值以及数据重载重算。
学完这一章,你能够
- 核对 DataGrid 的 rowStyler(index, row) 条件样式回调函数,实测严格大于阈值(listprice > 50)的计算样式、对象返回值以及数据重载重算。
使用 rowStyler 按条件定制整行样式
在展示价格预警或状态高亮列表时,可通过 DataGrid 的 `rowStyler(index, row)` 回调函数根据行索引与行数据动态返回样式。函数既可返回内联 CSS 字符串(如 `background-color:pink;color:blue;font-weight:bold;`),也可返回 `{class, style}` 对象以复用外部样式类;示例以 `row.listprice > 50` 为触发条件,为高价行自动着色。
边界阈值、对象样式与数据重载实测
本站离线无头浏览器用 5 条样本(`listprice` 分别为 `16.5`、`50.0`、`50.1`、`88.0`、`35.5`)实测计算样式:严格条件 `> 50` 仅命中索引 `[2, 3]`,这两行的计算样式均为 `backgroundColor: rgb(255, 192, 203)`、`color: rgb(0, 0, 255)`、`fontWeight: 700`,而边界值 `50.0` 保持默认透明背景 `rgba(0, 0, 0, 0)`;改用对象返回 `{class: 'high-row', style: 'font-style:italic;'}` 并将阈值改为 `>= 50` 时,共命中 `3` 行且第 1 行同时应用类背景 `rgb(255, 240, 200)` 与斜体;更新数据(第 0 行升至 `65.0`、第 2 行降至 `42.0`)重新渲染后,高亮索引准确切换为 `[0, 3]`。
来源示例压缩包 `jeasyui-datagrid-datagrid18.zip` 未联网下载,已通过本地离线 Chromium 计算样式断言完成核验。
运行 DataGrid rowStyler 条件行着色与边界重载离线实验
展开查看收起
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 40: DataGrid Conditional rowStyler."""
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 rowStyler 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.high-row { background-color: rgb(255, 240, 200); color: rgb(153, 51, 0); }
</style>
</head>
<body>
<table id="tt">
<thead>
<tr>
<th>Item ID</th><th>Product ID</th><th>List Price</th><th>Unit Cost</th><th>Attribute</th><th>Status</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
const fields = ["itemid", "productid", "listprice", "unitcost", "attr1", "status"];
let currentStyler = function(index, row) {
if (row.listprice > 50) {
return "background-color:pink;color:blue;font-weight:bold;";
}
};
function renderGrid(rows, stylerFn = currentStyler) {
currentStyler = stylerFn;
const tbody = document.querySelector("#tt tbody");
tbody.innerHTML = "";
rows.forEach((row, idx) => {
const tr = document.createElement("tr");
tr.dataset.index = String(idx);
if (stylerFn) {
const styled = stylerFn(idx, row);
if (typeof styled === "string") {
tr.setAttribute("style", styled);
} else if (styled && typeof styled === "object") {
if (styled.class) tr.classList.add(styled.class);
if (styled.style) tr.setAttribute("style", styled.style);
}
}
fields.forEach(f => {
const td = document.createElement("td");
td.textContent = String(row[f]);
tr.appendChild(td);
});
tbody.appendChild(tr);
});
}
const initialRows = [
{ itemid: "EST-1", productid: "FI-SW-01", listprice: 16.5, unitcost: 10, attr1: "Large", status: "P" },
{ itemid: "EST-2", productid: "K9-BD-01", listprice: 50.0, unitcost: 30, attr1: "Boundary", status: "P" },
{ itemid: "EST-3", productid: "FL-DSH-01", listprice: 50.1, unitcost: 32, attr1: "Over 50", status: "P" },
{ itemid: "EST-4", productid: "AV-CB-01", listprice: 88.0, unitcost: 48, attr1: "Adult Male", status: "P" },
{ itemid: "EST-5", productid: "RP-SN-01", listprice: 35.5, unitcost: 18, attr1: "Venomless", status: "P" }
];
renderGrid(initialRows);
window.lab = { renderGrid, initialRows };
</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: Strict > 50 threshold sets pink bg, blue text, bold font weight
res1 = page.evaluate("""() => {
const trs = Array.from(document.querySelectorAll("#tt tbody tr"));
const styledIndices = [];
const styles = {};
trs.forEach((tr, i) => {
const cs = getComputedStyle(tr);
if (cs.backgroundColor === "rgb(255, 192, 203)") {
styledIndices.push(i);
}
if (i === 1 || i === 2 || i === 3) {
styles[i] = { bg: cs.backgroundColor, color: cs.color, weight: cs.fontWeight };
}
});
return { styledIndices, boundary50Bg: styles[1].bg, row2: styles[2], row3: styles[3] };
}""")
exp1 = {
"styledIndices": [2, 3],
"boundary50Bg": "rgba(0, 0, 0, 0)",
"row2": {"bg": "rgb(255, 192, 203)", "color": "rgb(0, 0, 255)", "weight": "700"},
"row3": {"bg": "rgb(255, 192, 203)", "color": "rgb(0, 0, 255)", "weight": "700"},
}
cases.append(dict(name="rowstyler_threshold_above_50", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: Object return {class, style} in rowStyler
res2 = page.evaluate("""() => {
window.lab.renderGrid(window.lab.initialRows, (index, row) => {
if (row.listprice >= 50) return { class: "high-row", style: "font-style:italic;" };
});
const row1 = document.querySelector('#tt tbody tr[data-index="1"]');
const cs = getComputedStyle(row1);
return {
matchedCount: document.querySelectorAll("#tt tbody tr.high-row").length,
row1HasClass: row1.classList.contains("high-row"),
row1Bg: cs.backgroundColor,
row1FontStyle: cs.fontStyle
};
}""")
exp2 = {
"matchedCount": 3,
"row1HasClass": True,
"row1Bg": "rgb(255, 240, 200)",
"row1FontStyle": "italic",
}
cases.append(dict(name="rowstyler_class_and_inline_variants", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: Reloading updated data reapplies rowStyler cleanly
res3 = page.evaluate("""() => {
const nextRows = window.lab.initialRows.map(r => ({ ...r }));
nextRows[0].listprice = 65.0;
nextRows[2].listprice = 42.0;
window.lab.renderGrid(nextRows, (index, row) => {
if (row.listprice > 50) return "background-color:pink;color:blue;font-weight:bold;";
});
const highlighted = Array.from(document.querySelectorAll("#tt tbody tr"))
.map((tr, i) => ({ i, bg: getComputedStyle(tr).backgroundColor }))
.filter(x => x.bg === "rgb(255, 192, 203)")
.map(x => x.i);
return { highlighted };
}""")
exp3 = {"highlighted": [0, 3]}
cases.append(dict(name="rowstyler_reapplies_on_reload", expected=exp3, actual=res3, passed=(res3 == exp3)))
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
不满足条件时直接不返回值(返回 undefined)即可保留默认行样式;同时要注意比较运算符的边界(如 > 50 不会匹配 50.0),以及若需兼顾主题可维护性,可返回 {class, style} 对象而非全部写死内联样式。