API Document [zTree -- jQuery tree plug-ins.]
以上是tree结构的推荐学习网站
问题的起源是当时刚接需求的时候需要实现树表,在初次接触时确实出现了一些问题,用了些时间才弄出来, 不是驴不走就是磨不转,所以分享一下经验
树表后台就层级返回封装好的层级集合就行,一般多为三层结构,返回格式json串,定义请求节点如:
public class Ztree implements Serializable
这里挑重点来展示一下代码,需要注意的是如果数据量太大的情况下,可能会有错误,所以在做树的时候数据量需要结合实际情况去做判断
/**
* 查询部门管理树(排除下级)
*
* @param dept 部门
* @return 所有部门信息
*/
@Override
@DataScope(deptAlias = "d")
public List<Ztree> selectDeptTreeExcludeChild(SysDept dept)
{
Long deptId = dept.getDeptId();
List<SysDept> deptList = deptMapper.selectDeptList(dept);
Iterator<SysDept> it = deptList.iterator();
while (it.hasNext())
{
SysDept d = (SysDept) it.next();
if (d.getDeptId().intValue() == deptId
|| ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""))
{
it.remove();
}
}
List<Ztree> ztrees = initZtree(deptList);
return ztrees;
}
/**
* 对象转部门树
*
* @param deptList 部门列表
* @return 树结构列表
*/
public List<Ztree> initZtree(List<SysDept> deptList)
{
return initZtree(deptList, null);
}
这里需要设置你需要的节点去请求数据库得到相应的数据
/**
* 对象转部门树
*
* @param deptList 部门列表
* @param roleDeptList 角色已存在菜单列表
* @return 树结构列表
*/
public List<Ztree> initZtree(List<SysDept> deptList, List<String> roleDeptList)
{
List<Ztree> ztrees = new ArrayList<Ztree>();
boolean isCheck = StringUtils.isNotNull(roleDeptList);
for (SysDept dept : deptList)
{
if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()))
{
Ztree ztree = new Ztree();
ztree.setId(dept.getDeptId());
ztree.setpId(dept.getParentId());
ztree.setName(dept.getDeptName());
ztree.setTitle(dept.getDeptName());
//自定义判断是否是用户
if (!StringUtils.isNotNull(dept.getAncestors()) || "".equals(dept.getAncestors())){
ztree.setUser(true);
}
if (isCheck)
{
ztree.setChecked(roleDeptList.contains(dept.getDeptId() + dept.getDeptName()));
}
ztrees.add(ztree);
}
}
return ztrees;
}
前端主要是引包和节点控制
样式引包
<th:block th:include="include :: layout-latest-css"/>
<th:block th:include="include :: ztree-css"/>
js里需要引的包
<th:block th:include="include :: layout-latest-js"/>
<th:block th:include="include :: ztree-js"/>
首先先得有树请求去请求数据形成树结构,后台定义的节点请求参数
这里边就只有一个重要的就是treeNode.id是后端定义的一个请求参数,至于其他的都是点击之后节点的显示和隐藏
function queryDeptTree() {
var url = ctx + "system/dept/treeData";
var options = {
url: url,
expandLevel: 1,
onClick: zOnClick
};
$.tree.init(options);
function zOnClick(event, treeId, treeNode) {
$("#deptId").val(treeNode.id);
$("#parentId").val(treeNode.pId);
$.table.search();
}
}
$('#btnExpand').click(function () {
$._tree.expandAll(true);
$(this).hide();
$('#btnCollapse').show();
});
$('#btnCollapse').click(function () {
$._tree.expandAll(false);
$(this).hide();
$('#btnExpand').show();
});
$('#btnRefresh').click(function () {
queryDeptTree();
});
当你做完以上的事情 需要你在列表中进行放置这棵树,定义一个默认方法把以上
var panehHidden = false;
if ($(this).width() < 769) {
panehHidden = true;
}
$('body').layout({initClosed: panehHidden, west__size: 185});
// 回到顶部绑定
if ($.fn.toTop !== undefined) {
var opt = {
win: $('.ui-layout-center'),
doc: $('.ui-layout-center')
};
$('#scroll-up').toTop(opt);
}
queryDeptTree();