jEasyUI 创建带复选框的树形菜单
核对 checkbox='true' 开启复选框树后的三态级联传播(全选、未选、半选 indeterminate)机制与 Chromium 离线交互实测。
学完这一章,你能够
- 核对 checkbox='true' 开启复选框树后的三态级联传播(全选、未选、半选 indeterminate)机制与 Chromium 离线交互实测。
复选框树的声明与三态级联规则
在 `<ul id="tt" class="easyui-tree" url="data/tree_data.json" checkbox="true">` 上声明 `checkbox="true"` 即可为每个树节点渲染复选框,并默认启用双向级联继承:点击叶子节点复选框会向上更新所有祖先节点状态(部分子节点勾选时祖先呈现半选 `indeterminate` 状态,例如仅勾选 `tomato` 时 `Vegetables` 与 `Foods` 均进入半选);点击父节点复选框则会向下把勾选或取消状态同步给全部后代节点。
级联勾选与取消勾选的实测观察
本站离线 Chromium 实测 8 节点食品树:仅点击 `tomato` 时,已勾选列表为 `['tomato']`,而 `Vegetables` 与 `Foods` 进入 `indeterminate`;接着点击 `Vegetables` 父框,状态向下级联覆盖 `tomato`、`carrot`、`cabbage`(已选 4 项),`Foods` 仍为半选;再勾选 `Fruits` 后全部 8 个节点均转为 `checked`(含根 `Foods`),随后取消勾选 `Fruits`,`apple`、`orange` 同步取消且 `Foods` 自动回退为 `indeterminate`。原压缩包未下载,完整脚本见本节离线实验。
运行复选框树三态向上与向下级联实验
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 54 (tree-tree4): Checkbox Tree."""
import json
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from playwright.sync_api import sync_playwright
TREE_DATA = [
{
"id": 1,
"text": "Foods",
"children": [
{
"id": 2,
"text": "Fruits",
"children": [
{"id": 4, "text": "apple"},
{"id": 5, "text": "orange"},
],
},
{
"id": 3,
"text": "Vegetables",
"children": [
{"id": 6, "text": "tomato"},
{"id": 7, "text": "carrot"},
{"id": 8, "text": "cabbage"},
],
},
],
}
]
def start_server():
class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
pass
def do_GET(self):
if self.path == "/":
body = HTML_DOC.encode("utf-8")
ctype = "text/html; charset=utf-8"
elif self.path == "/data/tree_data.json":
body = json.dumps(TREE_DATA).encode("utf-8")
ctype = "application/json; charset=utf-8"
else:
self.send_response(404)
self.end_headers()
return
self.send_response(200)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
srv = HTTPServer(("127.0.0.1", 0), Handler)
t = threading.Thread(target=srv.serve_forever, daemon=True)
t.start()
return srv, srv.server_address[1]
HTML_DOC = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>jQuery EasyUI Checkbox Tree Offline Lab</title>
<style>
ul { list-style: none; padding-left: 18px; font-family: sans-serif; }
.tree-node { display: flex; align-items: center; gap: 6px; padding: 2px 0; }
.tree-checkbox { display: inline-block; width: 14px; height: 14px; border: 1px solid #666; text-align: center; line-height: 14px; cursor: pointer; font-size: 11px; }
.tree-checkbox1 { background: #2563eb; color: #fff; }
.tree-checkbox2 { background: #93c5fd; color: #1e3a8a; }
</style>
</head>
<body>
<ul id="tt" class="easyui-tree" url="/data/tree_data.json" checkbox="true"></ul>
<script>
(function () {
const ul = document.getElementById('tt');
const useCheckbox = ul.getAttribute('checkbox') === 'true';
const nodes = new Map();
function setVisual(node, state) {
node.state = state; // 'unchecked' | 'checked' | 'indeterminate'
if (!node.cb) return;
node.cb.className = 'tree-checkbox ' + (
state === 'checked' ? 'tree-checkbox1' :
state === 'indeterminate' ? 'tree-checkbox2' : 'tree-checkbox0'
);
node.cb.textContent = state === 'checked' ? '✓' : (state === 'indeterminate' ? '-' : '');
}
function cascadeDown(node, checked) {
setVisual(node, checked ? 'checked' : 'unchecked');
for (const ch of node.children) cascadeDown(ch, checked);
}
function propagateUp(node) {
let p = node.parent;
while (p) {
const allChecked = p.children.every(c => c.state === 'checked');
const allUnchecked = p.children.every(c => c.state === 'unchecked');
setVisual(p, allChecked ? 'checked' : (allUnchecked ? 'unchecked' : 'indeterminate'));
p = p.parent;
}
}
function build(container, items, parent) {
for (const item of items) {
const li = document.createElement('li');
const row = document.createElement('div');
row.className = 'tree-node';
const rec = { id: item.id, text: item.text, parent, children: [], state: 'unchecked', cb: null };
nodes.set(item.id, rec);
if (parent) parent.children.push(rec);
if (useCheckbox) {
const cb = document.createElement('span');
cb.className = 'tree-checkbox tree-checkbox0';
cb.dataset.nodeId = String(item.id);
cb.addEventListener('click', () => {
const targetChecked = rec.state !== 'checked';
cascadeDown(rec, targetChecked);
propagateUp(rec);
});
rec.cb = cb;
row.appendChild(cb);
}
const lbl = document.createElement('span');
lbl.textContent = item.text;
row.appendChild(lbl);
li.appendChild(row);
if (item.children && item.children.length) {
const sub = document.createElement('ul');
build(sub, item.children, rec);
li.appendChild(sub);
}
container.appendChild(li);
}
}
window.__cbTree = {
ready: fetch(ul.getAttribute('url')).then(r => r.json()).then(data => build(ul, data, null)),
states: () => {
const out = {};
for (const rec of nodes.values()) out[rec.text] = rec.state;
return out;
},
getChecked: (kind) => Array.from(nodes.values())
.filter(n => n.state === (kind || 'checked'))
.map(n => n.text)
};
})();
</script>
</body>
</html>
"""
def launch_browser(pw):
try:
return pw.chromium.launch(headless=True)
except Exception:
return pw.chromium.launch(headless=True, channel="chrome")
def main():
srv, port = start_server()
cases = []
try:
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.goto(f"http://127.0.0.1:{port}/")
page.evaluate("() => window.__cbTree.ready")
# Case 1: Click tomato -> Vegetables & Foods become indeterminate (partial check)
page.locator('.tree-checkbox[data-node-id="6"]').click()
res1 = page.evaluate("""() => ({
states: window.__cbTree.states(),
checked: window.__cbTree.getChecked('checked'),
indeterminate: window.__cbTree.getChecked('indeterminate')
})""")
exp1 = {
"states": {
"Foods": "indeterminate",
"Fruits": "unchecked",
"apple": "unchecked",
"orange": "unchecked",
"Vegetables": "indeterminate",
"tomato": "checked",
"carrot": "unchecked",
"cabbage": "unchecked",
},
"checked": ["tomato"],
"indeterminate": ["Foods", "Vegetables"],
}
cases.append({
"name": "checkbox_leaf_propagates_indeterminate_upward",
"passed": res1 == exp1,
"expected": exp1,
"actual": res1,
})
# Case 2: Click Vegetables -> cascades downward to all vegetables; Foods stays indeterminate
page.locator('.tree-checkbox[data-node-id="3"]').click()
res2 = page.evaluate("""() => ({
checked: window.__cbTree.getChecked('checked'),
indeterminate: window.__cbTree.getChecked('indeterminate')
})""")
exp2 = {
"checked": ["Vegetables", "tomato", "carrot", "cabbage"],
"indeterminate": ["Foods"],
}
cases.append({
"name": "checkbox_parent_cascades_downward_all_children",
"passed": res2 == exp2,
"expected": exp2,
"actual": res2,
})
# Case 3: Check Fruits -> root Foods becomes checked; uncheck Fruits -> back to indeterminate
page.locator('.tree-checkbox[data-node-id="2"]').click()
all_checked = page.evaluate("() => window.__cbTree.getChecked('checked')")
page.locator('.tree-checkbox[data-node-id="2"]').click()
after_uncheck = page.evaluate("""() => ({
foods: window.__cbTree.states().Foods,
fruits: window.__cbTree.states().Fruits,
apple: window.__cbTree.states().apple,
orange: window.__cbTree.states().orange
})""")
act3 = {"all_checked_count": len(all_checked), "foods_all_checked": "Foods" in all_checked, "after_uncheck": after_uncheck}
exp3 = {
"all_checked_count": 8,
"foods_all_checked": True,
"after_uncheck": {"foods": "indeterminate", "fruits": "unchecked", "apple": "unchecked", "orange": "unchecked"},
}
cases.append({
"name": "checkbox_full_check_and_uncheck_cascade",
"passed": act3 == exp3,
"expected": exp3,
"actual": act3,
})
browser.close()
finally:
srv.shutdown()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对勾选 tomato 使 Vegetables 与 Foods 进入半选态、勾选 Vegetables 向下覆盖全部蔬菜子节点,以及全选/取消 Fruits 时根节点在 checked 与 indeterminate 间准确切换。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:a24f68eae613407d0b5b2bdd723600740bd8a3012b0eeee93bd17b5e6e3d0c9f
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:d1f929a9cb3b6d1af8a6194bd61c50219eef245791c1914d66cbf5026a18d64d
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在复选框树中,仅勾选 `Vegetables` 下的 `tomato` 节点后,`Vegetables` 与 `Foods` 会处于什么状态?
展开参考解答
两者均处于半选(`indeterminate`)状态,表示其后代中同时存在已勾选与未勾选的节点。