目录
使用ztree过程中,发现ztree自带的getNodesByParamsFuzzy()方法,只能拿到当前节点,父级以上节点都获取不到。
于是采用了getNodesByFilter()方法,自定义所要过滤的值,再利用hideNodes()方法隐藏过滤出的值,实现了模糊搜素节点时连带展示所有上级节点的效果,也解决了隐藏方法导致的根节点无法显示(display:none)的问题。
Demo
-
HTML部分
<div>
<ul id="treeDemo" class="ztree"></ul>
</div>
-
JS部分
const searchVal = '1'; //模糊搜索值
const setting = {};
const zTreeObj;
// 数据
const zNodes = [
{
name: "test1", open: true, children: [
{
name: "test1_1", children: [{
name: "test333"
}]
}, {name: "test1_2"}]
},
{
name: "test2", open: true, children: [
{name: "test2_1"}, {name: "test2_2"}, {
name: "test2_4", children: [{
name: "test233"
}]
}]
}
];
// 初始化ztree
zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, zNodes);
const treeObj = $.fn.zTree.getZTreeObj("treeDemo");
// 需要隐藏的值
let hiddenNodes = treeObj.getNodesByFilter(filterFunc);
treeObj.hideNodes(hiddenNodes);
treeObj.expandAll(true);
function filterFunc(node) {
let selfMatch = node.name.includes(searchVal);
let childMatch = false;
// 过滤非匹配的值
return !recursion(node, selfMatch, childMatch);
}
// 递归
function recursion(node, selfMatch, childMatch) {
if (node.isParent) {
for (let i = 0; i < node.children.length; i++) {
if (node.children[i].name.includes(searchVal)) {
childMatch = true;
return selfMatch || childMatch;
} else {
childMatch = recursion(node.children[i], selfMatch, childMatch);
}
}
}
// 当自身匹配或者子节点匹配都返回true
return selfMatch || childMatch;
}
-
最终效果
全部数据如下
当模糊搜索值为1时,搜索后的结果如下