layui--tree--tree搜索功能
let id1 = ''
let id2 = ''
var tree1 = tree.render({
elem: '#test1' //绑定元素
,showLine:false
, id: "tree1"
,data: dataTree
,click: function(obj){
if (obj.data.id != id1) {
// 点击某一项高亮
$('div[id=test1] div[data-token operator">+ id1 + '"] span').eq(1).last().removeClass('custom-tree-item-clicked');
$('div[id=test1] div[data-token operator">+ obj.data.id + '"] span').eq(1).last().addClass("custom-tree-item-clicked");
}
id1 = obj.data.id
}
});
var tree2 = tree.render({
elem: '#test2' //绑定元素
,showLine:false
, id: "tree2"
,data: dataTree
,click: function(obj){
if (obj.data.id != id2) {
$('div[id=test2] div[data-token operator">+ id2 + '"] span').eq(1).last().removeClass('custom-tree-item-clicked');
$('div[id=test2] div[data-token operator">+ obj.data.id + '"] span').eq(1).last().addClass("custom-tree-item-clicked");
}
id2 = obj.data.id
}
});
$.ajax({
url:'树数据接口?id=""',
type:"get",
//type:"post",
//data:({}),
contentType: 'application/json',
dataType:"json",
headers:{
"token":localStorage.getItem("token") || "null"
},
success:function(data){
if(data.code=="0"){
dataTree = data.data.map(org => mapTree(org) )
tree.reload('tree1',{ data: dataTree }); // 树形组件重载
tree.reload('tree2',{ data: dataTree }); // 树形组件重载
} else {
layer.msg(data.msg,{icon:2,time: 4000});
}
}
})
// 树搜索框
// treeId: tree所在的容器的id
// filter: 对应的搜索框的selector或者dom对象
// callback: 回调 参数(树节点jquery对象, 输入框对象, 匹配到的节点数量)
tree.syncLayuiTreeFilter = function (treeId, filter, callback) {
let treeElem = $('#' + treeId), filterElem = $(filter);
if (!filterElem.length || !filterElem.length) {
return;
}
// 搜索框的监听事件按实际需求来 监听input框 输入时自动就开始搜索
filterElem.on("input",function () {
let that = this; //this;
let value = $(that).val().trim();
let HIDE = 'layui-hide';
let hintClass = 'search_hit';
// 先恢复现场
treeElem.find('.' + HIDE).removeClass(HIDE);
treeElem.find('.' + hintClass).removeClass(hintClass)
// 如果有值筛选开始
if (value) {
$.each(treeElem.find('.layui-tree-txt'), function (index, elem) {
elem = $(elem);
let textTemp = elem.text();
if (textTemp.indexOf(value) === -1) {
// 不存在就隐藏
elem.closest('.layui-tree-set').addClass(HIDE)
} else {
// 命中就添加一个class
elem.addClass(hintClass)
}
});
$.each(treeElem.find('.' + hintClass), function (index, elem) {
elem = $(elem);
// 取消隐藏所有父节点
elem.parents('.layui-tree-set').removeClass(HIDE);
// 展开所有父节点
elem.parents('.layui-tree-set').each(function (i, item) {
if (!$(item).hasClass('layui-tree-spread')) {
$(item).find('.layui-tree-iconClick :first').click();
}
});
});
}
typeof callback === 'function' && callback.call(that, treeElem, filterElem, treeElem.find('.' + hintClass).length);
});
};
tree.syncLayuiTreeFilter('test1','#search1',function (treeElem, filterElem, hitNumbers) {
// ('hitNumbers', hitNumbers);
// ('找到' + hitNumbers + '个节点');
});
tree.syncLayuiTreeFilter('test2','#search2',function (treeElem, filterElem, hitNumbers) {
// ('hitNumbers', hitNumbers);
// ('找到' + hitNumbers + '个节点');
});