Ztree行政地区树状展示(点击加载) 效果如下:
开始贴代码:
实体类 Item,用于对Ztree的节点展示
public class Item { private String id; private String pId; private String name; private int type; private String isParent; //getters/setters }
通过业务代码获取加载的对象:
@RequestMapping("/province/showProvince") @ResponseBody public List<Item> showProvince(HttpServletRequest request,Model model){ List<Province> all = provinceService.getAll(); List<Item> list = new ArrayList<Item>(all.size()); for(Province p : all){ Item item = new Item(); item.setId(p.getCode()); item.setpId("0"); item.setName(p.getProvinceName()); item.setIsParent("true"); item.setType(0); list.add(item); } return list; }
关键看页面的脚本和实现:
页面代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Insert title here</title> <link href="https://www.jb51.net/css/demo.css" type="text/css" /> <link href="https://www.jb51.net/css/zTreeStyle/zTreeStyle.css" type="text/css" /> <script type="text/javascript" src="https://www.jb51.net/js/jquery-1.4.4.min.js"></script> <script type="text/javascript" src="https://www.jb51.net/js/menu.js"></script> <script type="text/javascript" src="https://www.jb51.net/js/jquery.ztree.core-3.5.js"></script> </head> <body> <div> <ul></ul> </div> </body> </html>
menu.js
var menu = { setting : { data : { simpleData : { enable : true } }, keep : { parent : true }, /* * view : { dblClickExpand : false }, */ callback : { // 回调函数 onExpand : addNode, onClick : addNode } }, loadMenuTree : function() { $.post("province/showProvince.do", null, function(data) { $.fn.zTree.init($("#tree"), menu.setting, data); }); } }; $().ready(function() { menu.loadMenuTree(); }); function addNode(event, treeId, treeNode, clickFlag) { var zTree = $.fn.zTree.getZTreeObj("tree"); if (treeNode.isParent && typeof (treeNode.children) == "undefined") { var type = treeNode.type; var parameter = { pId : treeNode.id }; if (type == 0) { $.post("city/showCity.do", parameter, function(data) { zTree.addNodes(treeNode, data); }); } if (type == 1) { $.post("county/showCounty.do", parameter, function(data) { zTree.addNodes(treeNode, data); }); } } }
其中onExpand : addNode, onClick : addNode 两个回调函数,分别是在点击折叠按钮和节点时,异步加载子节点的内容,onDblClick添加回调函数时,发现会触发onExpand 事件,是因为zTree双击时触发onExpand事件,所以在setting中设置 view : { dblClickExpand : false } 可关闭这个默认设置。