一、显示ztree 的节点
1,前台转换显示 :
<div>
<ul id="tree" class="ztree"></ul>
</div>
通过jquery ajax 获得节点集合: nodelist
将数据转换成指定格式:
var treeNodes = [];
for(var i = 0; i < nodelist.length; i++){
treeNodes.push({id:nodelist[i].bm, parentId:nodelist[i].sjbm, name:nodelist[i].mc,open: ((nodelist[i].sjbm=='0000000') ? true : false),
tag:result[i]});
}
$.fn.zTree.init($("#tree"),selectionSetting, treeNodes);(selectionSetting 的定义省略)
2,后台转换显示:
代码:
/**
* 将科目数据转化成json格式的数据用于树控件
*/
public String getsubjectAll() {
JSONArray jsonArr = new JSONArray();
try {
List<HdzxKm> subjects = subjectDao.getSubjectAll();
for (HdzxKm subject : subjects) {
JSONObject json = new JSONObject();
json.put("id", subject.getBm());
json.put("name", subject.getMc());
if(如果是父级){
json.put("open", false);
}
json.put("parentId", subject.getSjbm());
jsonArr.add(json);
}
} catch (Exception e) {
e.printStackTrace();
}
return jsonArr.toString();
}
前台获得该方法返回的数据,就不用转换直接:
$.fn.zTree.init($("#tree"),selectionSetting, treeNodes);(selectionSetting 的定义省略)
treeNodes 为后台返回的数据
二、根据节点的id选中指定节点
var treeObj = $.fn.zTree.getZTreeObj("tree");
treeObj.selectNode(treeObj.getNodeByParam("id","000000000000", null));(000000000000:节点Id的值)
三、自定义修改节点的名称(根据节点id值)
var treeObj = $.fn.zTree.getZTreeObj("tree");
var node = treeObj.getNodeByParam("id", id的值, null);
node.name="xxxxx";
treeObj.updateNode(node,true);(此处为更新节点值,此步不能省)
四、新增节点
var treeObj = $.fn.zTree.getZTreeObj("tree");
var node = treeObj.getNodeByParam("id", xxx, null);
treeObj.addNodes(node, {id :xxx,parentId :xxx,name : xxx});
五、有复选框是,选中指定节点
var zTree =$.fn.zTree.getZTreeObj("tree");
var node=zTree.getNodeByParam("id",id值, null);
zTree.checkNode(node);