使用Ztree实现目录树
目标实现。点击按钮,出现目录结构树。可以单击选择节点,选中之后树隐藏,节点展示在input中。
HTML代码如下:
1 <div class="form-group"> 2 <label class="col-lg-2 col-md-2 col-sm-2 col-xs-2 control-label"> 3 核准目录</label> 4 <div class="col-lg-9 col-md-9 col-sm-9 col-xs-9"> 5 <input type="text" class="form-control" placeholder="" data-related='true' id='textAPPROVE_INDUSTRY' name='textAPPROVE_INDUSTRY' 6 readonly value="${data.attrs.formInfo.textAPPROVE_INDUSTRY}" /> 7 </div> 8 <label class="col-lg-1 col-md-1 col-sm-1 col-xs-1 text-left control-label" style="text-align: left;"> 9 <span id="menuAPPROVE_INDUSTRYBtn" class="tableBtn" data-show="false">选择</span> 10 </label> 11 <input type="hidden" id="APPROVE_INDUSTRY" data-related='true' name='APPROVE_INDUSTRY' value="${data.attrs.formInfo.APPROVE_INDUSTRY}" /> 12 </div>
JS代码:
第一步、引入ztree.js
1 /** 2 * 绑定树 3 */ 4 $.fn.zTree.init($("#treeAPPROVE_INDUSTRY"), settingHzml);
实现setting
1 /** 2 * setting设置 3 */ 4 var settingHzml = { 5 view: { 6 selectedMulti: false 7 }, 8 async: { 9 enable: true, // 启用异步加载 10 url:"" 后台请求数据地址, // 调用的后台的方法 11 autoParam: ["id"], // 向后台传递的参数 12 dataFilter: filterHzml 13 }, 14 callback: { 15 beforeClick: beforeClickHzml 16 } 17 };
实现filter
1 function filterHzml(treeId, parentNode, childNodes) { 2 var array = []; 3 childNodes = childNodes.invDictHzmls;//获取后台传递的数据 4 if (!childNodes) return null; 5 for (var i = 0, l = childNodes.length; i < l; i++) { 6 repname = childNodes[i].NAME.replace(/\.n/g, '.'); 7 8 //将后台传过来的参数拼接成json格式,并放在数组中,如果有必要需要对其是否为父节点做处理 9 if (childNodes[i].isParent) { 10 array[i] = { id: childNodes[i].ID, name: repname, code2: childNodes[i].CODE2, code: childNodes[i].CODE, isParent: true }; 11 } else { 12 array[i] = { id: childNodes[i].ID, name: repname, code2: childNodes[i].CODE2, code: childNodes[i].CODE, isParent: false }; 13 } 14 } 15 return array; 16 }
实现callback
1 function beforeClickHzml(treeId, treeNode) { 2 if (!treeNode.isParent) { 3 $("#textAPPROVE_INDUSTRY").val(treeNode.name); 4 $("#APPROVE_INDUSTRY").val(treeNode.code); 5 $("#label_textAPPROVE_INDUSTRY5").text(treeNode.name); 6 hideMenuHzml(); 7 return false; 8 } else { 9 return true; 10 } 11 }
效果展示:
点击后