hn_cloud_web/public/login/js/treeBind.js

99 lines
2.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 通用树组件:绑定一个树选择器
function bindTreeSelector(options) {
const {
inputTextId, // 点击显示树的文本框 ID
inputValueId, // 隐藏 valueID字段 ID
panelId, // 树的弹出容器 ID
treeId, // zTree 的 <ul> 元素 ID
ajaxUrl, // 获取树结构的接口
extraSet = null // 点击节点时执行的额外逻辑(可选)
} = options;
let panelVisible = false;
// 1. 初始化树
function loadTree() {
$.ajax({
type: "post",
url: ajaxUrl,
dataType: "json",
headers: {
Authorization: "Bearer " + localStorage.getItem("public_token"),
},
success: function (res) {
$.fn.zTree.init($("#" + treeId), {
view: { dblClickExpand: false, selectedMulti: false, nameIsHTML: true },
data: { simpleData: { enable: true } },
callback: {
onClick: onNodeClick
}
}, res.data || res.obj);
},
error: function () {
console.error("树加载失败:" + ajaxUrl);
}
});
}
loadTree();
// 2. 显示/隐藏
function togglePanel() {
if (panelVisible) {
hidePanel();
} else {
const $input = $("#" + inputTextId);
const pos = $input.position();
$("#" + panelId)
.css({
left: pos.left + "px",
top: pos.top + $input.outerHeight() + "px",
width: $input.outerWidth() + "px"
})
.slideDown("fast");
panelVisible = true;
}
}
function hidePanel() {
$("#" + panelId).fadeOut("fast");
panelVisible = false;
}
// 3. 点击树节点事件
function onNodeClick(event, tid, node) {
if (!node) return;
const zTree = $.fn.zTree.getZTreeObj(treeId);
const pathNodes = node.getPath();
let pathText = pathNodes.map(n => n.name).join("/");
let idValue = node.id;
$("#" + inputTextId).val(pathText);
$("#" + inputValueId).val(idValue);
if (extraSet && typeof extraSet === "function") {
extraSet(node);
}
hidePanel();
}
// 4. 点击输入框显示树
$("#" + inputTextId).on("click", function () {
togglePanel();
return false;
});
// 点击空白关闭(如需要)
$(document).on("click", function (e) {
if (!$(e.target).closest("#" + panelId).length &&
!$(e.target).is("#" + inputTextId)) {
hidePanel();
}
});
}