常规的ztree树
后台数据封装成list对象
public PageModel getTreeBuildingRegData(Map<String, String> params) {PageModel pageModel=new PageModel();String status=params.get("status");String orgId=params.get("org_id");List<OmsBuildingReg> regList = new ArrayList<OmsBuildingReg>();StringBuffer hql = new StringBuffer(" from OmsBuildingReg t where 1=1 ");//分状态查询if(StringUtils.isNotBlank(status)){hql.append(" and t.status='"+status+"'");}//分机构查询if(StringUtils.isNotBlank(orgId)){orgId = orgId.replace(",", "','");hql.append(" and t.orgId in('"+orgId+"')");}regList = this.omsBuildingRegDao.findHql(hql.toString());List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();Map<String,Object> map = null;for (OmsBuildingReg reg : regList) {map = new HashMap<String,Object>();map.put("chkDisabled",false);map.put("click", true);map.put("id", reg.getId());map.put("name", reg.getChName());map.put("nocheck", false);map.put("struct","TREE");map.put("title",reg.getChName());//有性别时,添加性别属性map.put("otherParam", reg.getBuildingSex() + "@@" + reg.getBuildingType());if (StringUtils.isNotBlank(reg.getParentBuildingId())) {map.put("parentId",reg.getParentBuildingId());}else {map.put("parentId","0");}dataList.add(map);}pageModel.setData(dataList);return pageModel;}
前台js 树展示
var ztreeCreator = new ZtreeCreator('regTree',path +"/sys/sysCall?bs_code=S_00117",zNodes).setCallback({onClick:zTreeOnLeftClick,onRightClick:zTreeOnRightClick}).initZtree({},function(treeObj){regTree = treeObj});
ztreeCreator.js
/*** 构造Ztree 说明。* * 快速构造默认配置的ztree* new ZtreeCreator('treeId',url).initZtree(param); * treeId:树的Id,url:请求的url , * initZtree(param,level,call); * parma 异步请求提供参数,* level展开层级(可略,默认展开全部),* call 回调提供Ztree初始化对象 *** 完整例子* var ztreeCreator = new ZtreeCreator('groupTree',url)* .setCallback({beforeClick:beforeClick,onClick:zTreeOnLeftClick,onRightClick:zTreeOnRightClick})* .initZtree(params,function(treeObj){groupTree=treeObj}); *****/var ZtreeCreator = function(treeId,url,initJson){if(!treeId) alert("构造Ztree必须提供 treeId");this.treeId = treeId;var _treeObj;var outLookStyle =false;/**初始化树**/ this.initZtree = function(param,level,callBack){if(!url && !_setting.async.url) alert("构造Ztree必须提供 请求地址!");if (jQuery.isFunction(param)) {callBack = param;param = {}; }if (jQuery.isFunction(level)) {callBack = level; level = false;}if(!param) param = {};// 通过json初始化树if(initJson){pushJsonToBuildTree(initJson,level,callBack);return this;}//传入自定义设置参数if(param.setting){this.setSetingParam(param.setting);}//如果异步加载if(_setting.async.url){_treeObj=jQuery.fn.zTree.init(jQuery("#"+treeId), _setting);return this;}//一次性加载 jQuery.post(url,param,function(result){if(Object.prototype.toString.call(result) === "[object String]") result =eval('(' + result + ')');pushJsonToBuildTree(result,level,callBack);});return this;}function pushJsonToBuildTree(json,level,callBack){_treeObj = jQuery.fn.zTree.init(jQuery("#"+treeId),_setting,json);//展开层级if(level){_treeObj.expandAll(false);expandTree(_treeObj,_treeObj.getNodes(),level);}else{ _treeObj.expandAll(true); }if(jQuery.isFunction(callBack)) callBack(_treeObj,treeId); if(outLookStyle){try{var curMenu = _treeObj.getNodes()[0].children[0].children[0];}catch(e){}_treeObj.selectNode(curMenu);}}this.getTreeObj = function(){if(!_treeObj) alert(treeId+"尚未初始化");return _treeObj;};/**设置树展示的标识key {idKey:"idKEY名称",pIdKey:"",name:"显示名称",title,rootPid}* idKey 默认 id* pIdKey 默认 parentId* name 默认 name* title 默认 name* */this.setDataKey = function(keys){if(!keys) return this;if(keys.idKey) _setting.data.simpleData.idKey = keys.idKey;if(keys.pIdKey) _setting.data.simpleData.pIdKey = keys.pIdKey;if(keys.name) _setting.data.key.name = keys.name;if(keys.title) _setting.data.key.title = keys.title;if(keys.rootPId) _setting.data.simpleData.rootPId=keys.rootPId;return this;}this.setChildKey = function(key){if(!key)key = "children";_setting.data.simpleData.enable = false;_setting.data.key.children =key;return this;}/** 设置选择框的方式默认没有选择框* 如果需要选择框,不需要级联 则传 true* param true or { "Y": "p", "N": "s" }*/this.setCheckboxType = function(type){_setting.check.enable = trueif(type instanceof Object){_setting.check.chkboxType = type;}return this;}/**这里支持Ztree 所有的回调方法,请查API* eg:传入参数{beforeClick:beforeClick,onClick:onClick,beforeCheck:beforeCheck}**/this.setCallback = function(callBack){if(callBack instanceof Object) for(call in callBack){if(!jQuery.isFunction(callBack[call])) alert(call+" :is not a function");_setting.callback[call] = callBack[call];}return this; }/** 异步加载 */this.setAsync = function(conf){_setting.async = conf;return this; }/**是否显示图标配置项**/this.setShowIcon = function(call){_setting.view.showIcon = call;return this; }/**设置一些特殊的值请参照 Ztree _setting 格式 ***/this.setSetingParam = function(param){if(param instanceof Object) for(p in param){_setting[p] = param[p];}return this; }this.setOutLookStyle =function(){//设置一些参数 this.setSetingParam({view :{showLine: false, showIcon: true,selectedMulti: false, dblClickExpand: false,addDiyDom: function(treeId, treeNode){var spaceWidth = 15;var switchObj = jQuery("#" + treeNode.tId + "_switch"),icoObj = jQuery("#" + treeNode.tId + "_ico");switchObj.remove();if(!treeNode.children ||treeNode.children.length==0){switchObj.removeClass("switch");}icoObj.before(switchObj);if (treeNode.level > 0){var spaceStr = "<span style='display: inline-block;width:" + (spaceWidth * treeNode.level)+ "px'></span>";switchObj.before(spaceStr);}}}});jQuery("#"+treeId).addClass("showIcon"); outLookStyle =true;return this;}/**** 注意。isShowIn!= treeId,当前情况treeId可以随意写。只要唯一即可* isShowIn,被显示在某个元素下面,比如 input框,做成累似comboTree的样子* width,height 设置出现 那个 combox的宽高* TODO 如果是input 设置 autoSetValue = true , 扩展回显和自动填值功能。*/var _isShowIn,_menuContent;this.makeCombTree = function(isShowIn,width,height){height = height? height:300;width =width ? width:163;_menuContent = treeId+"MenuContent";_isShowIn = isShowIn; var menuContent ='<div id="'+_menuContent+'" style="width:'+width+'px; height:'+height+'px;overflow-y:scroll; position:absolute;z-index: 9999;display:none;background-color:#F5F5F5">'+'<ul id="'+treeId+'" class="ztree" ></ul></div>';jQuery("#"+isShowIn).after(menuContent); jQuery("#"+isShowIn).bind("click",this.showMenu); return this;}// 可以添加一个目标对象,如果是添加了点击事件的,则默认this.showMenu = function(target){if(!target || target.currentTarget) {target = jQuery(this);}var btnOffset = target.offset();jQuery("#"+_menuContent).css({left:btnOffset.left + "px", top:btnOffset.top + target.outerHeight() + "px"}).slideDown("fast");jQuery("body").bind("mousedown",onBodyDown);}this.hideMenu =function(){hideMenu(); }var onBodyDown = function (event){if (!(event.target.id == _isShowIn || event.target.id == _menuContent || jQuery(event.target).parents("#"+_menuContent).length>0)){hideMenu();}}var hideMenu = function(){jQuery("#"+_menuContent).fadeOut("fast");jQuery("body").unbind("mousedown", onBodyDown);}/**_setting 私有 配置项**/ var _setting = {data: {key:{name: "name",title: "name"},simpleData: {enable: true,idKey: "id",pIdKey: "parentId",rootPId:0}},async: {enable: false},edit: {drag: {isCopy:true},enable: true,showRemoveBtn: false,showRenameBtn: false},view:{nameIsHTML: true,selectedMulti: true,showIconFont:true,showIcon: null},check: {enable: false,chkboxType: { "Y": "", "N": "" }},callback:{beforeClick: null,onClick: null,onRightClick: null,beforeDrop: null,onDrop: null,onAsyncSuccess: null}}/***设置展开层级*/function expandTree(treeObj,nodes,level){var thelevel=level-1; for(var i=0;i<nodes.length;i++){var node =nodes[i];treeObj.expandNode(node, true, false, false); if(thelevel>0 && node.children && node.children.length>0){expandTree(treeObj, node.children,thelevel); } } }};
左击、右击事件
//左击 function zTreeOnLeftClick(event, treeId, treeNode) {curSelectNode = treeNode;var parentId = treeNode.id;var url = "departController.do?update&id=" + curSelectNode.id;if(curSelectNode.parentId=="0"){$.topCall.warn('该节点为根节点,请点击具体的组织');return false;}$("#listFrame").attr("src", url); }; /*** 树右击事件*/ function zTreeOnRightClick(e, treeId, treeNode) { if (treeNode) {orgTree.selectNode(treeNode);curSelectNode=treeNode;var isfolder = treeNode.isFolder;var h = $(window).height();var w = $(window).width();var menuWidth = 120;var menuHeight = 75;var menu = null;if (treeNode != null) {menu = $('#orgMenu');}var x = e.pageX, y = e.pageY;if (e.pageY + menuHeight > h) {y = e.pageY - menuHeight;}if (e.pageX + menuWidth > w) {x = e.pageX - menuWidth;}menu.menu('show', {left : x,top : y});}
//不是根节点时把添加根节点置灰
if(buildingType!=1){
$('#regMenu').menu('disableItem', $('#addTopMenu'));
}else{
$('#regMenu').menu('enableItem', $('#addTopMenu'));
}
//最后一个子节点时不让添加
if(buildingType==5){
$('#regMenu').menu('disableItem', $('#addMenu'));
}else{
$('#regMenu').menu('enableItem', $('#addMenu'));
}
}; //菜单对应项 function menuHandler(item) {if ('add' == item.name) {addNode();} else if ('remove' == item.name) {delNode();} else if ('sort' == item.name) {sortNode();} else if ('edit' == item.name) {editNode(1);} else if ('fresh' == item.name) {refreshNode();} }; function refreshNode() {loadTree(); };//添加节点 function addNode() {var selectNode = getSelectNode();if (!selectNode) return;var url = "departController.do?add&id=" + selectNode.id;$("#listFrame").attr("src", url);};//编辑节点 function editNode(type) {var selectNode = getSelectNode();if (!selectNode) return;//根节点 不能编辑if(selectNode.id=="0" && type==1 ){$.topCall.warn('该节点为根节点,不可编辑');return;}var url = "departController.do?update&id=" + selectNode.id;$("#listFrame").attr("src", url);};//删除 function delNode() {var selectNode = getSelectNode();var nodeId = selectNode.id;if (nodeId == "0") {$.topCall.warn('该节点为根节点,不可删除');return;} var url = "jeecgFormDemoController.do?del&id="+nodeId;if(!confirm('温馨提示', '确定删除该组织以及该组织下的所有子组织?')){return;}jQuery.ajax({ async : false, cache:false, type: 'GET', dataType : "json", url: url,//请求的action路径 error: function () {//请求失败处理函数 alert('请求失败'); }, success:function(data){ //请求成功后处理函数。if(data.success){orgTree.removeNode(selectNode);$("#listFrame").attr("src", "about:blank");}else{alert(data.msg);}} }); }; //选择资源节点。 function getSelectNode() {orgTree = $.fn.zTree.getZTreeObj("orgTree");var nodes = orgTree.getSelectedNodes();var node = nodes[0];return node; };
带 radio 的单选下拉菜单
将官网上的demo拷贝一份出来
var setting = {check: {enable: true,chkStyle: "radio",radioType: "all"},view: {dblClickExpand: false},data: {simpleData: {enable: true}},callback: {onClick: onClick,onCheck: onCheck}};function showMenu() {jQuery.ajax({async : false,type : 'POST',dataType : "json",data:{status:"1",buildingType:"1,2,3,4"},url : path + "/sys/sysCall?bs_code=S_00151",error : function() {//请求失败处理函数 console.log("123");alert('请求失败');},success : function(data) { //请求成功后处理函数。 console.log(data);zNodes=data.data;$.fn.zTree.init($("#treeDemo"), setting, zNodes);}});var cityObj = $("#parentBuildingId");var cityOffset = $("#parentBuildingId").offset();$("#menuContent").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast");$("body").bind("mousedown", onBodyDown); }function onBodyDown(event) {if (!(event.target.id == "menuBtn" || event.target.id == "parentBuildingId" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {hideMenu();} } function hideMenu() {$("#menuContent").fadeOut("fast");$("body").unbind("mousedown", onBodyDown); }function onClick(e, treeId, treeNode) {var zTree = $.fn.zTree.getZTreeObj("treeDemo");zTree.checkNode(treeNode, !treeNode.checked, null, true);return false; }function onCheck(e, treeId, treeNode) {var zTree = $.fn.zTree.getZTreeObj("treeDemo"),nodes = zTree.getCheckedNodes(true),v = "";for (var i=0, l=nodes.length; i<l; i++) {v += nodes[i].name + ",";}if (v.length > 0 ) v = v.substring(0, v.length-1);var cityObj = $("#parentBuildingId");cityObj.attr("value", v); }
定义input框、div,div先隐藏掉,设置样式
<input id="parentBuildingId" name="parentBuildingId" type="text" class="form-control" οnclick="showMenu();" /><div id="menuContent" class="menuContent" style="display:none; position: absolute;"><ul id="treeDemo" class="ztree" style="margin-top:0; width:100%;background-color:#f9f9f9"></ul></div>
后台填充数据。
public PageModel getSelectTreeBuildingRegData(Map<String, String> params){PageModel pageModel=new PageModel();String status=params.get("status");String orgId=params.get("org_id");String buildingType=params.get("buildingType");try{List<OmsBuildingReg> regList = new ArrayList<OmsBuildingReg>();StringBuffer hql = new StringBuffer(" from OmsBuildingReg t where 1=1 ");//分状态查询if(StringUtils.isNotBlank(status)){hql.append(" and t.status='"+status+"'");}//分机构查询if(StringUtils.isNotBlank(orgId)){orgId = orgId.replace(",", "','");hql.append(" and t.orgId in('"+orgId+"')");}if(StringUtils.isNotBlank(buildingType)){buildingType = buildingType.replace(",", "','");hql.append(" and t.buildingType in('"+buildingType+"')");}regList = this.findHql(hql.toString());List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();Map<String,Object> map = null;for (OmsBuildingReg reg : regList) { // StringBuilder sqls = new StringBuilder();; // Object[] paramss = null;map = new HashMap<String,Object>();map.put("id", reg.getId());map.put("name", reg.getChName());if (StringUtils.isNotBlank(reg.getParentBuildingId())) {map.put("pId",reg.getParentBuildingId());map.put("open",false);}else {map.put("pId","1");map.put("open",false);} // sqls.append(" from OmsBuildingReg t where t.parentBuildingId=? ") ; // //分机构查询 // if(StringUtils.isNotBlank(orgId)){ // orgId = orgId.replace(",", "','"); // sqls.append(" and t.orgId in('"+orgId+"')"); // } // paramss = new Object[]{reg.getId()}; // List<OmsBuildingReg> omsBuildingRegList= this.findHql(sqls.toString(), paramss); // if(omsBuildingRegList!=null&&omsBuildingRegList.size()>0){ // dataList.add(map); // }else{ // OmsBuildingReg de = this.getEntity(OmsBuildingReg.class, reg.getId()); // if (de != null) { // map.put("id", de.getId()); // map.put("name", de.getChName()); // if(StringUtils.isNotBlank(de.getParentBuildingId())){ // map.put("pId", reg.getParentBuildingId()); // map.put("open",false); // }else{ // map.put("pId", "1"); // map.put("open",false); // } // dataList.add(map); // }else{ // map.put("open",false); // dataList.add(map); // } // } dataList.add(map);pageModel.setMsg("查询成功");}pageModel.setData(dataList);}catch(Exception e){e.printStackTrace();}return pageModel;} }
效果图: