jEasyUI 树形菜单拖放控制
核对 dnd: true 启用树节点拖放、onDrop(targetNode, source, point) 持久化回调与循环父子防护机制的 Chromium 实测。
学完这一章,你能够
- 核对 dnd: true 启用树节点拖放、onDrop(targetNode, source, point) 持久化回调与循环父子防护机制的 Chromium 实测。
开启树节点拖放(dnd: true)
要允许用户通过鼠标拖拽调整树节点层级与同级顺序,只需在初始化配置中将 `dnd` 设为 `true`(`$('#tt').tree({ dnd: true, url: 'tree_data.json' })`)。拖拽放置支持三种相对落点 `point`:`append` 表示成为目标节点的子节点,`top` 与 `bottom` 分别表示插入到目标节点的上方或下方。
监听 onDrop 同步服务端与边界防护
节点放置完成后组件触发 `onDrop(targetNode, source, point)` 事件,其中 `targetNode` 是落点对应的 DOM 元素,需借助树实例的 `getNode(targetNode)`(如 `$(this).tree('getNode', targetNode).id`,原片段写作 `$(target)` 实操中应指向树容器本身)提取 `targetId`,再通过 POST 将 `{id: source.id, targetId, point}` 持久化至服务端。
本站通过本地回环 `/save_drop` 接口实测:将 `apple(4)` 以 `point='append'` 拖入 `Vegetables(3)` 后,`Fruits` 仅余 `orange`、`Vegetables` 变为 `['tomato', 'carrot', 'apple']`,服务端准确记录 `{id: 4, targetId: 3, point: 'append'}`;再将 `orange(5)` 以 `point='top'` 放到 `tomato(6)` 之前,`Vegetables` 顺序更新为 `['orange', 'tomato', 'carrot', 'apple']` 且服务端收到 `point='top'`;此外将祖先节点 `Foods(1)` 拖入其后代 `Vegetables(3)` 或关闭 `dnd=false` 时均被拦截且不触发额外请求。原示例压缩包未下载。
运行树形菜单拖放改父、同级插序与持久化回调实验
展开查看收起
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 55 (tree-tree5): Tree Drag & Drop."""
import json
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs
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"},
],
},
],
}
]
def start_server():
drop_events = []
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 == "/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)
def do_POST(self):
if self.path == "/save_drop":
length = int(self.headers.get("Content-Length", "0"))
params = parse_qs(self.rfile.read(length).decode("utf-8"))
rec = {
"id": int(params["id"][0]),
"targetId": int(params["targetId"][0]),
"point": params["point"][0],
}
drop_events.append(rec)
body = json.dumps({"ok": True, "saved": rec}).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
else:
self.send_response(404)
self.end_headers()
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], drop_events
HTML_DOC = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>jQuery EasyUI Tree DnD Offline Lab</title>
<style>
ul { list-style: none; padding-left: 16px; font-family: sans-serif; }
.tree-node { padding: 3px 6px; border: 1px solid transparent; }
</style>
</head>
<body>
<ul id="tt"></ul>
<script>
(function () {
const ul = document.getElementById('tt');
let cfg = { dnd: true, onDrop: null };
function build(container, items) {
for (const item of items) {
const li = document.createElement('li');
li.dataset.nodeId = String(item.id);
const row = document.createElement('div');
row.className = 'tree-node';
row.dataset.id = String(item.id);
row.dataset.text = item.text;
row.textContent = item.text;
li.appendChild(row);
if (item.children && item.children.length) {
const sub = document.createElement('ul');
build(sub, item.children);
li.appendChild(sub);
}
container.appendChild(li);
}
}
function getNode(el) {
return { id: Number(el.dataset.id), text: el.dataset.text, target: el };
}
async function performDrop(sourceId, targetId, point) {
if (!cfg.dnd) return { moved: false, reason: 'dnd_disabled' };
const srcLi = ul.querySelector(`li[data-node-id="${sourceId}"]`);
const tgtLi = ul.querySelector(`li[data-node-id="${targetId}"]`);
if (!srcLi || !tgtLi || srcLi === tgtLi || srcLi.contains(tgtLi)) {
return { moved: false, reason: 'invalid_cycle_or_same' };
}
const source = getNode(srcLi.querySelector(':scope > .tree-node'));
const targetNode = tgtLi.querySelector(':scope > .tree-node');
if (point === 'append') {
let sub = tgtLi.querySelector(':scope > ul');
if (!sub) {
sub = document.createElement('ul');
tgtLi.appendChild(sub);
}
sub.appendChild(srcLi);
} else if (point === 'top') {
tgtLi.parentElement.insertBefore(srcLi, tgtLi);
} else if (point === 'bottom') {
tgtLi.parentElement.insertBefore(srcLi, tgtLi.nextSibling);
}
if (cfg.onDrop) {
await cfg.onDrop(targetNode, source, point);
}
return { moved: true };
}
function childrenTexts(id) {
const li = ul.querySelector(`li[data-node-id="${id}"]`);
const sub = li ? li.querySelector(':scope > ul') : null;
if (!sub) return [];
return Array.from(sub.querySelectorAll(':scope > li > .tree-node')).map(e => e.dataset.text);
}
window.$ = (sel) => ({
tree: (arg1, arg2) => {
if (typeof arg1 === 'object') {
cfg = Object.assign({ dnd: false }, arg1);
return fetch(cfg.url).then(r => r.json()).then(data => build(ul, data));
}
if (arg1 === 'getNode') return getNode(arg2);
if (arg1 === 'options') return cfg;
}
});
window.__dndReady = $('#tt').tree({
dnd: true,
url: '/tree_data.json',
onDrop: async function (targetNode, source, point) {
const targetId = $('#tt').tree('getNode', targetNode).id;
await fetch('/save_drop', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `id=${source.id}&targetId=${targetId}&point=${encodeURIComponent(point)}`
});
}
});
window.__performDrop = performDrop;
window.__childrenTexts = childrenTexts;
window.__setDnd = (flag) => { cfg.dnd = flag; };
})();
</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, drop_events = 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.__dndReady")
# Case 1: Drop apple(4) onto Vegetables(3) with point='append'
r1 = page.evaluate("""async () => {
const status = await window.__performDrop(4, 3, 'append');
return {
status,
fruits: window.__childrenTexts(2),
vegetables: window.__childrenTexts(3)
};
}""")
act1 = {**r1, "server_events": list(drop_events)}
exp1 = {
"status": {"moved": True},
"fruits": ["orange"],
"vegetables": ["tomato", "carrot", "apple"],
"server_events": [{"id": 4, "targetId": 3, "point": "append"}],
}
cases.append({
"name": "tree_dnd_append_reparent_and_post",
"passed": act1 == exp1,
"expected": exp1,
"actual": act1,
})
# Case 2: Drop orange(5) before tomato(6) with point='top'
r2 = page.evaluate("""async () => {
const status = await window.__performDrop(5, 6, 'top');
return {
status,
fruits: window.__childrenTexts(2),
vegetables: window.__childrenTexts(3)
};
}""")
act2 = {**r2, "last_event": drop_events[-1]}
exp2 = {
"status": {"moved": True},
"fruits": [],
"vegetables": ["orange", "tomato", "carrot", "apple"],
"last_event": {"id": 5, "targetId": 6, "point": "top"},
}
cases.append({
"name": "tree_dnd_top_insert_and_onDrop_point",
"passed": act2 == exp2,
"expected": exp2,
"actual": act2,
})
# Case 3: Ancestor-into-descendant cycle blocked & dnd=false guard
r3 = page.evaluate("""async () => {
const cycle = await window.__performDrop(1, 3, 'append');
window.__setDnd(false);
const disabled = await window.__performDrop(6, 2, 'append');
return { cycle, disabled };
}""")
act3 = {**r3, "total_server_events": len(drop_events)}
exp3 = {
"cycle": {"moved": False, "reason": "invalid_cycle_or_same"},
"disabled": {"moved": False, "reason": "dnd_disabled"},
"total_server_events": 2,
}
cases.append({
"name": "tree_dnd_cycle_and_disabled_guards",
"passed": act3 == exp3,
"expected": exp3,
"actual": act3,
})
browser.close()
finally:
srv.shutdown()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`targetNode` 是放置目标的 DOM 元素,`source` 是被拖拽节点的数据对象,`point` 指示落点位置(`append`、`top` 或 `bottom`);服务端只有同时获知 `targetId` 与 `point`,才能区分是更改父节点还是调整同级排序。