Recently, because work requires a tree drop-down box component, there are generally two implementation methods after searching for information. First, it is implemented using zTree; second, it is implemented using easyUI. Because the front-end of the company is not designed using easyUI, I chose zTree to implement the drop-down tree here.
Here, a simple data format (i.e. a simple Json format) is used similar to the following Json:
var zNodes =[ {id:1, pId:0, name:"Beijing"}, {id:2, pId:0, name:"Tianjin"}, {id:3, pId:0, name:"Shanghai"}, {id:6, pId:0, name:"Chongqing"}, {id:4, pId:0, name:"Hebei Province", open:true, nocheck:true}, {id:41, pId:4, name:"Shijiazhuang"}, {id:42, pId:4, name:"Baoding"}, {id:43, pId:4, name:"Handan"}, {id:44, pId:4, name:"Chengde"}, {id:5, pId:0, name:"Guangdong Province", open:true, nocheck:true}, {id:51, pId:5, name:"Guangzhou"}, {id:52, pId:5, name:"Shenzhen"}, {id:53, pId:5, name:"Dongguan"}, {id:54, pId:5, name:"Foshan"}, {id:6, pId:0, name:"Fujian Province", open:true, nocheck:true}, {id:61, pId:6, name:"Fuzhou"}, {id:62, pId:6, name:"Xiamen"}, {id:63, pId:6, name:"Quanzhou"}, {id:64, pId:6, name:"Sanming"} ];Here, an entity bean is first needed to encapsulate the corresponding found data, as follows:
public class ZtreeNode { // id private String id; // Parent id private String pId; // Display name private String name; // Whether to open (the default is not opened here, if it needs to be opened, set to true) // private boolean open; // Can you select (set whether the node can be selected by default, and the node corresponding to set to true cannot be selected) // private boolean nocheck ; /**getter and setter*/}It should be noted here that the second letter in pId is capitalized. If written in lowercase, it cannot be constructed into a tree structure. All are root nodes.
Then, convert the data found from the database into the corresponding beans required by ztree, and then convert it into the corresponding Json. The code is as follows:
// Get the product classification tree and return json public String getGoodsCategoryTreeJson() { List<GoodsCategory> allGoodsCategoryList = goodsCategoryService.getGoodsCategoryTreeJson() ; List<ZtreeNode> ztreelist = new ArrayList<ZtreeNode>(); for(GoodsCategory gcty : allGoodsCategoryList){ ZtreeNode treenade = new ZtreeNode(); treenade.setId(gcty.getId()); treenade.setpId(gcty.getParent()==null?"":gcty.getParent().getId()); treenade.setName(gcty.getName()); ztreelist.add(treenade); } return ajax(ztreelist); }Convert list to the corresponding Json method, as follows:
The Json toolkit used:
import org.springframework.base.util.JsonUtil;private static final String HEADER_ENCODING = "UTF-8";private static final boolean HEADER_NO_CACHE = true;private static final String HEADER_TEXT_CONTENT_TYPE = "text/plain";private static final String HEADER_JSON_CONTENT_TYPE = "text/plain";// AJAX output protected String ajax(String content, String contentType) { try { HttpServletResponse response = initResponse(contentType); response.getWriter().write(content); response.getWriter().flush(); } catch (IOException e) { e.printStackTrace(); } return NONE; } // Output AJAX protected String ajax(String text) { return ajax(text, HEADER_TEXT_CONTENT_TYPE); } // Output AJAX protected String ajax(Status status) { HttpServletResponse response = initResponse(HEADER_JSON_CONTENT_TYPE); Map<String, String> jsonMap = new HashMap<String, String>(); jsonMap.put(STATUS_PARAMETER_NAME, status.toString()); JsonUtil.toJson(response, jsonMap); return NONE; } //Output AJAX protected String ajax(Status status, String message) { HttpServletResponse response = initResponse(HEADER_JSON_CONTENT_TYPE); Map<String, String> jsonMap = new HashMap<String, String>(); jsonMap.put(STATUS_PARAMETER_NAME, status.toString()); jsonMap.put(MESSAGE_PARAMETER_NAME, message); JsonUtil.toJson(response, jsonMap); return NONE; } // Output AJAX protected String according to Object ajax(Object object) { HttpServletResponse response = initResponse(HEADER_JSON_CONTENT_TYPE); JsonUtil.toJson(response, object); return NONE; } //Output according to boolean status AJAX protected String ajax(boolean booleanStatus) { HttpServletResponse response = initResponse(HEADER_JSON_CONTENT_TYPE); Map<String, Object> jsonMap = new HashMap<String, Object>(); jsonMap.put(STATUS_PARAMETER_NAME, booleanStatus); JsonUtil.toJson(response, jsonMap); return NONE; } private HttpServletResponse initResponse(String contentType) { HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType(contentType + ";charset=" + HEADER_ENCODING); if (HEADER_NO_CACHE) { response.setDateHeader("Expires", 1L); response.addHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache, no-store, max-age=0"); } return response; }In this way, the data required by the front desk is taken out of the library and encapsulated into the corresponding Json.
Next is the implementation of the front desk. The js and css that the front desk needs to import are as follows:
<link rel="stylesheet" href="${base}/template/ztree/css/demo.css" type="text/css"><link rel="stylesheet" href="${base}/template/ztree/css/zTreeStyle/zTreeStyle.css" type="text/css"><script type="text/javascript" src="${base}/template/ztree/js/jquery.ztree.core.js"></script>Here, only demo.css is added by itself, and the others are officially formulated. demo.css is used to modify the css used by the official demo, as follows (there are redundant styles here that have not been deleted);
div.content_wrap {width: 400px;}div.content_wrap div.left{float: left;}div.content_wrap div.right{float: right;width: 340px;}div.zTreeDemoBackground {text-align:left;}ul.ztree {margin-top: 10px;border: 1px solid #617775;background: #fefefe;width:220px;height:360px;overflow-y:scroll;overflow-x:auto;}ul.log {border: 1px solid #617775;background: #f0f6e4;width:300px;height:170px;overflow: hidden;}ul.log.small {height:45px;}ul.log li {color: #666666;list-style: none;padding-left: 10px;}ul.log li.dark {background-color: #E3E3E3;}/* ruler */div.ruler {height:20px; width:220px; background-color:#f0f6e4;border: 1px solid #333; margin-bottom: 5px; cursor: pointer}div.ruler div.cursor {height:20px; width:30px; background-color:#3C6E31; color:white; text-align: right; padding-right: 5px; cursor: pointer}Then, the corresponding drop-down box:
<div> <input id="citySel" type="text" onclick="showMenu(); return false;" readonly value=""/> <input id="treeids" type="hidden" name="goods.goodsCategory.id" > <input type="button" onclick="showMenu();" value="∨"> </div></div> 8<div id="menuContent" style="display:none; position: absolute;"> <ul id="treeDemo" style="margin-top:0;"></ul></div>
Here is a hidden text box to store the corresponding id of the drop-down box selection content.
The corresponding scripts are as follows:
<SCRIPT type="text/javascript"> var setting = { view: { dblClickExpand: false }, data: { simpleData: { enable: true } }, callback: { onClick: onClick }, view: { // The corresponding icon is not displayed showIcon: false } }; function onClick(e, treeId, treeNode) { var zTree = $.fn.zTree.getZTreeObj("treeDemo"), nodes = zTree.getSelectedNodes(), v = ""; ids = ""; nodes.sort(function compare(a,b){return a.id-b.id;}); for (var i=0, l=nodes.length; i<l; i++) { v += nodes[i].name + ","; ids += nodes[i].id + ","; } if (v.length > 0 ) v = v.substring(0, v.length-1); var cityObj = $("#citySel"); cityObj.attr("value", v); // Put the selected id in the hidden text field if (ids.length > 0 ) ids = ids.substring(0, ids.length-1); var treeids = $("#treeids"); treesids.attr("value", ids); } function showMenu() { var cityObj = $("#citySel"); var cityOffset = $("#citySel").offset(); $("#menuContent").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast"); $("body").bind("mousedown", onBodyDown); } function hideMenu() { $("#menuContent").fadeOut("fast"); $("body").unbind("mousedown", onBodyDown); } function onBodyDown(event) { if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) { hideMenu(); } } var zNodes ; $(document).ready(function(){ // Load data $.ajax({ async : false, cache:false, type: 'POST', dataType : 'json', url: '${base}/admin/goods!getGoodsCategoryTreeJson.action', error: function () { alert('Request failed'); }, success:function(data){ zNodes = data; } }); $.fn.zTree.init($("#treeDemo"), setting, zNodes); }); </SCRIPT>In this way, a drop-down box is finished.
As shown in the figure below:
If you need to write back the corresponding drop-down list data in the modification page, add the following script:
<script type="text/javascript">$(document).ready(function(){ if ("${goods.goodsCategory.id}"!="") { var treeObj = $.fn.zTree.getZTreeObj("treeDemo"); var node = treeObj.getNodeByParam("id", "${goods.goodsCategory.id}" , null); treeObj.selectNode(node,false , false); onClick(event,"${goods.goodsCategory.id}",node,true); }});</script>The above is all about this article, I hope it will be helpful to everyone to learn the zTree plug-in.