layui版本:2.5.4
layui官网在2.5.0版本后才将树组件文档公布出来,实现方式和数据结构与之前的版本有了较大的改变。使用时发现搜索功能还未展示到文档中,参考 Fly社区的回答自己改动了下。
效果演示
//实现
// 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;
}
// 搜索框的监听事件按实际需求来
filterElem.unbind('change').change(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','#search',function (treeElem, filterElem, hitNumbers) {
console.log('hitNumbers', hitNumbers);
layer.msg('找到' + hitNumbers + '个节点');
});
树的初始化、点击行样式修改
layui.use('tree', function () {
let tree = layui.tree,
$ = layui.$;
// 测试数据
const data = [{
title: '湖北' //一级菜单
, children: [{
title: '武汉' //二级菜单
, children: [{
title: '江汉区' //三级菜单
}, {
title: '洪山区' //三级菜单
}, {
title: '江岸区' //三级菜单
}, {
title: '汉阳区' //三级菜单
}]
}]
}, {
title: '浙江' //一级菜单
, children: [{
title: '杭州' //二级菜单
, children: [{
title: '西湖区' //三级菜单
}, {
title: '上城区' //三级菜单
}, {
title: '下城区' //三级菜单
}, {
title: '滨江区' //三级菜单
}]
}]
}, {
title: '陕西' //一级菜单
, children: [{
title: '西安' //二级菜单
}]
}];
//渲染
tree.render({
elem: '#test1' //绑定元素
, data: data
, onlyIconControl: true
, click: function (obj) {
layer.msg(obj.data.title);
}
});
// 树点击样式修改
$("body").on("click", ".layui-tree-txt", function () {
$(".layui-tree-entry").removeClass("current");
$(this).parent().parent().addClass("current");
});
});
点击修改样式其实只是加了个背景色,可按自己需要定义
<style>
.current{background-color: #dbeef5}
</style>
转载:https://blog.csdn.net/zjh19961213/article/details/96427655/
Comments NOTHING