首先,layui环境搭建,ztree环境引入
ztree的js和css都要引入,我这里暂时用的是core包>
静态,一句话就够了
<!-- 左侧菜单树形组件 -->
<div class="layui-col-md3">
<div class="layui-footer ">
<h1>左侧菜单树形组件</h1>
<ul id="menuTree" class="ztree"></ul>
</div>
</div>
js,这里主要就是格式要跟ztree对应
childNodes[i].isParent = childNodes[i].isParent; 千万不要忽略这个参数
// 定义菜单树的模块
var MenuTree = {
init: function () {
// 初始化菜单树
var setting = {
view: {
selectedMulti: false
},
async: {
enable: true,
url:"youurl",
autoParam:["id=node"],
otherParam:{"otherParam":"zTreeAsyncTest"},
dataFilter: filter
},
callback: {
beforeClick: beforeClick,
beforeAsync: beforeAsync,
onAsyncError: onAsyncError,
onAsyncSuccess: onAsyncSuccess
}
};
function filter(treeId, parentNode, childNodes) {
if (!childNodes) return null;
for (var i=0, l=childNodes.length; i<l; i++) {
childNodes[i].name = childNodes[i].text;
childNodes[i].pId = childNodes[i].parentId;
childNodes[i].isParent = childNodes[i].isParent;
}
return childNodes;
}
function beforeClick(treeId, treeNode) {
if (!treeNode.isParent) {
alert("请选择父节点");
return false;
} else {
return true;
}
}
var log, className = "dark";
function beforeAsync(treeId, treeNode) {
className = (className === "dark" ? "":"dark");
showLog("[ "+getTime()+" beforeAsync ] " + ((!!treeNode && !!treeNode.name) ? treeNode.name : "root") );
return true;
}
function onAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) {
showLog("[ "+getTime()+" onAsyncError ] " + ((!!treeNode && !!treeNode.name) ? treeNode.name : "root") );
}
function onAsyncSuccess(event, treeId, treeNode, msg) {
showLog("[ "+getTime()+" onAsyncSuccess ] " + ((!!treeNode && !!treeNode.name) ? treeNode.name : "root") );
}
function showLog(str) {
if (!log) log = $("#log");
log.append("<li class='"+className+"'>"+str+"</li>");
if(log.children("li").length > 8) {
log.get(0).removeChild(log.children("li")[0]);
}
}
function getTime() {
var now= new Date(),
h=now.getHours(),
m=now.getMinutes(),
s=now.getSeconds(),
ms=now.getMilliseconds();
return (h+":"+m+":"+s+ " " +ms);
}
function refreshNode(e) {
var zTree = $.fn.zTree.getZTreeObj("menuTree"),
type = e.data.type,
silent = e.data.silent,
nodes = zTree.getSelectedNodes();
if (nodes.length == 0) {
alert("请先选择一个父节点");
}
for (var i=0, l=nodes.length; i<l; i++) {
zTree.reAsyncChildNodes(nodes[i], type, silent);
if (!silent) zTree.selectNode(nodes[i]);
}
}
$.fn.zTree.init($("#menuTree"), setting);
$("#refreshNode").bind("click", {type:"refresh", silent:false}, refreshNode);
$("#refreshNodeSilent").bind("click", {type:"refresh", silent:true}, refreshNode);
$("#addNode").bind("click", {type:"add", silent:false}, refreshNode);
$("#addNodeSilent").bind("click", {type:"add", silent:true}, refreshNode);
}
};