先引入ztree的几个依赖文件:
<link rel="stylesheet" href="lib/zTree/v3/css/zTreeStyle/zTreeStyle.css" type="text/css"> <script type="text/javascript" src="lib/zTree/v3/js/jquery-1.4.4.min.js"></script> <script type="text/javascript" src="lib/zTree/v3/js/jquery.ztree.core-3.5.js"></script> <script type="text/javascript" src="lib/zTree/v3/js/jquery.ztree.excheck-3.5.js"></script>
html中写:
<ul id="treeDemo" class="ztree"></ul>
js中配置:
<script type="text/javascript"> var setting = { check: { enable: true, chkStyle: "radio", radioType: "all" }, data: { simpleData: { enable: true } }, callback: { onCheck: onCheck //回调选择 } }; var zNodes =[ { id:1, pId:0, name:"鸡鸣寺",nocheck:true}, //表示没有单选框 { id:11, pId:1, name:"地点一",nocheck:true}, { id:111, pId:11, name:"二食堂"}, { id:112, pId:11, name:"三食堂"}, { id:12, pId:1, name:"地点二",nocheck:true}, { id:121, pId:12, name:"地点2-1"}, { id:122, pId:12, name:"地点2-2"} ]; function onCheck(e, treeId, treeNode){ var zTree = $.fn.zTree.getZTreeObj("treeDemo"); nodes = zTree.getCheckedNodes(true);//获取所选你的id值
var txt = ""; //获取所有的最底层的叶子节点的id for (var i = 0; i < nodes.length; i++) { if (nodes[i].isParent) { } else { txt += nodes[i].id + ","; } } // txt = txt.replace("null,", ""); //替换选择父节点的id txt = txt.substring(0, txt.length - 1); //alert(txt);
selVal = nodes[0].id; $("#sel").val(selVal); } $(document).ready(function(){ $.fn.zTree.init($("#treeDemo"), setting, zNodes);//初始化 }); </script>
最后运行的结果为:
复选框改一个
chkStyle: "checkbox",