1.首先需要引入的js/css
<link rel="stylesheet" href="ztree/css/zTreeStyle/zTreeStyle.css" type="text/css" />
<script type="text/javascript" src="ztree/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="ztree/js/jquery.ztree.core-3.5.min.js"></script>
<script type="text/javascript" src="ztree/js/jquery.ztree.exhide-3.5.min.js"></script>
exhide这个文件必须引入否则无法做筛选
2.html
<body>
<div >
<div class="search-bar">
<input id="keyword" type="text" placeholder="搜索菜单">
<button id="search-bt">搜索</button>
</div>
<div class="content">
<ul id="treeDemo" class="ztree"></ul>
</div>
</div>
</body>
3.js部分
(这里用的是静态数据,也可以异步加载数据,不影响筛选)
var hiddenNodes=[]; //用于存储被隐藏的结点
$(function(){
init();
})
function init(){
var zNodes=[ //ztree 测试数据,也可以从数据库拉取
{
name:"根节点",
open:true,
children:[
{
name:"父节点A1",
open:true,
children:[
{
name:"子节点A11"
},
{
name:"子节点A12"
},
{
name:"子节点A13"
},
{
name:"子节点A14"
}
]
},{
name:"父节点B1",
open:true,
children:[
{
name:"子节点B11"
},
{
name:"子节点B12"
},
{
name:"子节点B13"
},
{
name:"子节点B14"
}
]
},
]
}
];
var setting = { //ztree配置选项
data: {
key: {
name:"name",
title: "name"
}
}
//在这里可是使用异步加载async
};
zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, zNodes);
//或者$.fn.zTree.init($("#treeDemo"), setting);也是可以的
$("#search-bt").click(filter);
};
//过滤ztree显示数据
function filter(){
//显示上次搜索后背隐藏的结点
zTreeObj.showNodes(hiddenNodes);
//查找不符合条件的叶子节点
function filterFunc(node){
var _keywords=$("#keyword").val();
if(node.isParent||node.name.indexOf(_keywords)!=-1) return false;
return true;
};
//获取不符合条件的叶子结点
hiddenNodes=zTreeObj.getNodesByFilter(filterFunc);
//隐藏不符合条件的叶子结点
zTreeObj.hideNodes(hiddenNodes);
};
网友评论