1.静态树:
目录结构:(css与js为下载的原文件夹)
代码
zTree测试
测试:
点击树:
点击复选框:
2.动态生成带点击事件的树
页面中准备树位置
部门
Js请求树数据与生成树结构:
$(function() { alert(contextPath) var zNodes10; $.ajax({ url : contextPath + '/exam_getDepartmentTree.action', async : true, dataType : 'json', success : function(response) { zNodes10 = response.departmentTrees; // 生成树结构 geneDepartmentTree(zNodes10); }, error : function() { alert("查询内部部门树失败!!!") } }); }//生成树函数function geneDepartmentTree(departmentTrees) { var setting = { view : { selectedMulti : false }, check : { enable : true }, data : { simpleData : { enable : true, enable : true, idKey : "departmentId", pIdKey : "upDepartmentId", rootPId : null }, key : { name : "departmentName", } }, callback : { onClick : zTreeOnClick } }; var treeNodes = departmentTrees; $.fn.zTree.init($("#treeDemo"), setting, treeNodes);}// 鼠标点击树事件(打印点击的id与名字)function zTreeOnClick(event, treeId, treeNode) { alert(treeNode.departmentId + ", " + treeNode.departmentName);}
后台返回的JSON数据格式:(主要返回部门ID,上级ID,部门姓名即可构成一颗树)
{"departmentTrees":[{"departmentId":"10","departmentName":"厂级-1"},{"departmentId":"10001","departmentName":"部门1_10","upDepartmentId":"10"},{"departmentId":"10001001","departmentName":"班组1_10001","upDepartmentId":"10001"},{"departmentId":"10002","departmentName":"部门2_10","upDepartmentId":"10"},{"departmentId":"10002001","departmentName":"班组2_10002","upDepartmentId":"10002"},{"departmentId":"10003","departmentName":"部门3_10","upDepartmentId":"10"},{"departmentId":"11","departmentName":"厂级-2"},{"departmentId":"11001","departmentName":"部门1_11","upDepartmentId":"11"},{"departmentId":"12","departmentName":"厂级-3"}]}
结果:
点击树:
3.更复杂的关于树的点击事件参考:
另一个例子:(带有单选按钮的树)
******S QLQ**********************/var zTree;var setting = { check:{ enable:true, chkStyle :"radio", radioType: "all" }, data : { key : { name:"typeName" }, simpleData : { enable : true, idKey: "typeId", pIdKey: "upId", rootPId: 1 } }, callback : { onClick : clickNode //点击节点触发的事件 }};function geneTypeTree(){ $.getJSON(contextPath+"/trainacontentType_getTraincontenttypeTree.action",function(response){ var zNodes = response.traincontenttypeTree; zTree = $.fn.zTree.init($("#tree"),setting,zNodes); });}/************S 点击事件*********/function clickNode(e, treeId,treeNode) { $("#trainContentTypeId").val(treeNode.typeId);//向隐藏的类别编号赋值 $("[name='typeId']").val(treeNode.typeId);//向隐藏的类别编号赋值 $("#yeHao").val("1"); btnFindFy();}/************E 点击事件*********/function openModal(){ $("#el_empTrainDoc").modal("show");}/******E QLQ**********************/