layui版本:2.5.4
layui官网在2.5.0版本后才将树组件文档公布出来,实现方式和数据结构与之前的版本有了较大的改变。使用时发现搜索功能还未展示到文档中,参考 Fly社区的回答自己改动了下。
效果演示
主体实现
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;
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 {
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
>