jquery zTree异步加载、模糊搜索简单实例分享
本文实例为大家讲解了jqueryzTree树插件的基本使用方法,具体内容如下
一、节点模糊搜索功能:搜索成功后,自动高亮显示并定位、展开搜索到的节点。
二、节点异步加载:1、点击展开时加载数据;2、选中节点时加载数据。
前台代码如下:
<scripttype="text/javascript"> //ztree设置 varsetting={ view:{ fontCss:getFontCss }, check:{ enable:true }, data:{ simpleData:{ enable:true, idKey:"id", pIdKey:"pId", rootPId:0 } }, async:{ enable:true, url:"#{getStudentsJsonUrl}", autoParam:["id","level"] }, callback:{ beforeCheck:zTreeBeforeCheck, onNodeCreated:zTreeOnNodeCreated, beforeExpand:zTreeBeforeExpand } }; varreloadFlag=false;//是否重新异步请求 varcheckFlag=true;//是否选中 //节点展开前 functionzTreeBeforeExpand(treeId,treeNode){ reloadFlag=false; returntrue; }; //节点创建后 functionzTreeOnNodeCreated(event,treeId,treeNode){ varzTree=$.fn.zTree.getZTreeObj(treeId); if(reloadFlag){ if(checkFlag){ zTree.checkNode(treeNode,true,true); } if(!treeNode.children){ zTree.reAsyncChildNodes(treeNode,"refresh"); } } }; //选中节点前 functionzTreeBeforeCheck(treeId,treeNode){ varzTree=$.fn.zTree.getZTreeObj(treeId); if(!treeNode.children){ reloadFlag=true; checkFlag=true; zTree.reAsyncChildNodes(treeNode,"refresh"); } returntrue; } //页面加载完成 _run(function(){ require(['zTree/js/jquery.ztree.all-3.5'],function(){ $.ajax({ type:"POST", url:"#{getStudentsJsonUrl}", success:function(data){ if(data&&data.length!=0){//如果结果不为空 $.fn.zTree.init($("#tree"),setting,data); } else{//搜索不到结果 } } }); }); //提交 $("#inputSubmit").click(function(){ varzTree=$.fn.zTree.getZTreeObj("tree"); varnodes=zTree.getCheckedNodes(true); varids=""; varnames=""; for(vari=0;i<nodes.length;i++){//遍历选择的节点集合 if(!nodes[i].isParent){ ids+=nodes[i].id.replace("level"+nodes[i].level,"")+","; names+=nodes[i].name+","; } } Simpo.ui.box.hideBox(); parent.$(".boxFrm").contents().find("#inputRange").val(names.substr(0,names.length-1)); parent.$(".boxFrm").contents().find("#hidRange").val(ids.substr(0,ids.length-1)); }) }); //查找节点 varlastNodeList=[]; varlastKey; functionsearchNode(){ varzTree=$.fn.zTree.getZTreeObj("tree"); varkey=$.trim($("#inputSearchNode").val()); if(key!=""&&key!=lastKey){ nodeList=zTree.getNodesByParamFuzzy("name",key); for(vari=0,l=lastNodeList.length;i<l;i++){//上次查询的节点集合取消高亮 lastNodeList[i].highlight=false; zTree.updateNode(lastNodeList[i]); } zTree.expandAll(false);//全部收缩 if(nodeList.length>0){ for(vari=0,l=nodeList.length;i<l;i++){//遍历找到的节点集合 if(nodeList[i].getParentNode()){ zTree.expandNode(nodeList[i].getParentNode(),true,false,false);//展开其父节点 } nodeList[i].highlight=true; zTree.updateNode(nodeList[i]); } } zTree.refresh();//很重要,否则节点状态更新混乱。 lastNodeList=nodeList; lastKey=key; } } //加载数据 functionloadData(){ varzTree=$.fn.zTree.getZTreeObj("tree"); varrootNodes=zTree.getNodes(); reloadFlag=true; checkFlag=false; for(vari=0;i<rootNodes.length;i++){ if(!rootNodes[i].children){ zTree.reAsyncChildNodes(rootNodes[i],"refresh");//异步加载 } } } //全部收缩 functioncloseAll(){ varzTree=$.fn.zTree.getZTreeObj("tree"); if($("#inputCloseAll").val()=="全部收缩"){ zTree.expandAll(false); $("#inputCloseAll").val("全部展开") } else{ zTree.expandAll(true); $("#inputCloseAll").val("全部收缩") } } //高亮样式 functiongetFontCss(treeId,treeNode){ return(treeNode.highlight)?{color:"#A60000","font-weight":"bold"}:{color:"#333","font-weight":"normal"}; } </script>
<divstyle="width:200px;height:260px;overflow:auto;border:solid1px#666;"> <ulid="tree"class="ztree"> </ul> </div>
后台代码(后台返回Json数据):
publicvoidSelStudent() { set("getStudentsJsonUrl",to(GetStudentsJson)); } publicvoidGetStudentsJson() { List<Dictionary<string,string>>dicList=newList<Dictionary<string,string>>(); stringlevel=ctx.Post("level"); stringid=ctx.Post("id"); if(strUtil.IsNullOrEmpty(id)) { #region加载班级 //获取当前登录用户 Sys_Useruser=AdminSecurityUtils.GetLoginUser(ctx); //获取当前用户关联的老师 Edu_Teacherteacher=edu_TeacService.FindByUserId(user.Id); //获取班级集合 List<Edu_ClaNameFlow>list=edu_ClaNameFlowService.GetListByTeacherId(teacher.Id); foreach(Edu_ClaNameFlowiteminlist) { Dictionary<string,string>dic=newDictionary<string,string>(); dic.Add("id","level0"+item.Calss.Id.ToString()); dic.Add("pId","0"); dic.Add("name",item.Gra.Name+item.Calss.Name); dic.Add("isParent","true"); dicList.Add(dic); } #endregion } else { if(level=="0") { //加载学生 List<Edu_Student>list=edu_StudService.GetListByClassId(id.Replace("level0","")); foreach(Edu_Studentiteminlist) { Dictionary<string,string>dic=newDictionary<string,string>(); dic.Add("id","level1"+item.Id.ToString()); dic.Add("pId",id); dic.Add("name",item.Name); dic.Add("isParent","false"); dicList.Add(dic); } } } echoJson(dicList); }
三、基于cookie实现zTree树刷新后,展开状态不变
1、除了引用jQuery和zTree的JS外,引用cookie的JS:
<scripttype="text/javascript"src="~/Scripts/jquery-treeview/lib/jquery.cookie.js"></script>
2、JS代码:
$(function(){ //ztree设置 varsetting={ data:{ simpleData:{ enable:true, idKey:"id", pIdKey:"pId", rootPId:null } }, callback:{ onExpand:onExpand, onCollapse:onCollapse } }; $.ajax({ type:"POST", url:"/Tech/TemplateTypeManage/GetData", success:function(data){ if(data&&data.length!=0){ $.fn.zTree.init($("#tree"),setting,data); vartreeObj=$.fn.zTree.getZTreeObj("tree"); varcookie=$.cookie("z_tree"+window.location); if(cookie){ z_tree=JSON2.parse(cookie); for(vari=0;i<z_tree.length;i++){ varnode=treeObj.getNodeByParam('id',z_tree[i]) treeObj.expandNode(node,true,false) } } } } }); });//end$ functiononExpand(event,treeId,treeNode){ varcookie=$.cookie("z_tree"+window.location); varz_tree=newArray(); if(cookie){ z_tree=JSON2.parse(cookie); } if($.inArray(treeNode.id,z_tree)<0){ z_tree.push(treeNode.id); } $.cookie("z_tree"+window.location,JSON2.stringify(z_tree)) } functiononCollapse(event,treeId,treeNode){ varcookie=$.cookie("z_tree"+window.location); varz_tree=newArray(); if(cookie){ z_tree=JSON2.parse(cookie); } varindex=$.inArray(treeNode.id,z_tree); z_tree.splice(index,1); for(vari=0;i<treeNode.children.length;i++){ index=$.inArray(treeNode.children[i].id,z_tree); if(index>-1)z_tree.splice(index,1); } $.cookie("z_tree"+window.location,JSON2.stringify(z_tree)) }
更多关于ztree控件的内容,请参考专题《jQuery插件ztree使用汇总》
以上就是关于树插件zTree异步加载、模糊搜索简单实例讲解,希望对大家的学习有所帮助。