jquery zTree异步搜索的例子--搜全部节点

参考博客:

https://segmentfault.com/a/1190000004657854

https://blog.csdn.net/houpengfei111/article/details/8696436

https://blog.csdn.net/qq_36785111/article/details/78873488

这里思路是:

先异步加载所有节点,同时判断所有节点是否异步加载完毕,如果所有节点全部加载完毕时设置搜索按钮可点击;

搜索方法根据所有节点进行模糊查询getNodesByParamFuzzy,然后将查找到的节点和其所有父节点显示,其他节点隐藏;

 

代码:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="resources/zTreeStyle/zTreeStyle.css" type="text/css">
<link rel="stylesheet" type="text/css" href="resources/bootstrap/bootstrap.min.css">
<title>index</title>
</head>
<body>
    <div class="container">
        <h4>Ztree异步加载使用例子</h4>
        <input type="text" id="search" /> &nbsp; <input type="button" id="btn" value="搜素" onclick="search()"/>
        <ul id="zTree" class="ztree"></ul>
    </div>
</body>
<script src="resources/js/jquery.min.js"></script>
<script type="text/javascript" src="resources/js/jquery.ztree.all.min.js"></script>
<script type="text/javascript" src="resources/js/jquery.ztree.exhide.min.js"></script>
<script type="text/javascript">
var setting = {
        async: {
            enable: true,
            url:"asyncGetNodes",
            autoParam:["id", "pid", "name"],
            dataFilter: filter
        },
        data:{
            simpleData:{
                enable: true,
                idKey:'id',
                pIdKey:'pid',
                rootPId: 0
            }
        },
        view:{
            showIcon: false
        },
        callback: {
            onAsyncSuccess:onAsyncSuccess
          }
};
$(document).ready(function(){
    initZTree();
});


/**
 * 节点加载完的回调函数,加载方式依旧是分批加载,但是不是等用户展开节点才去加
 * 载,而是让它自动完成加载,这里不好的地方是依旧要加载全部数据,所以必须等待
 * 它加载完才能使用搜索功能 
 */
function onAsyncSuccess(event, treeId, treeNode, msg) {
    //console.log('success');
    var zTreeObj = $.fn.zTree.getZTreeObj(treeId);
    var nodes = zTreeObj.transformToArray(zTreeObj.getNodes()); 
    for (var i = 0; i < nodes.length; i++) {
        // 判断节点是否已经加载过,如果已经加载过则不需要再加载
         if (!nodes[i].zAsync) {
             zTreeObj.reAsyncChildNodes(nodes[i], 'refresh', true);
         }
    }
}


function filter(treeId, parentNode, childNodes) {
    return childNodes;
}

//初始化树
function initZTree(){
    $.ajax({
          url:"asyncGetNodes",
          type:"post",
          dataType: "json",
          success: function(data){
              console.log(data);
              var zTreeObj = $.fn.zTree.init($("#zTree"),setting, data); 
              //让第一个父节点展开
              var rootNode_0 = zTreeObj.getNodeByParam('pid',0,null);
              zTreeObj.expandNode(rootNode_0, true, false, false, false);
              console.log('expended');
              
              //搜索按钮不可用
              $('#btn').attr('disabled','disabled');
              
              zTreeAsyncReady('zTree',function(){
                 console.log('已经全部加载完了'); 
                 $('#btn').removeAttr('disabled','disabled');
              });
          },
          error: function(){
              
          }
      });
}

//判断树节点是否已经全部加载完
function zTreeAsyncReady(treeId, f){
     var zTreeObj = $.fn.zTree.getZTreeObj(treeId); 
     
     zTreeAsyncReady.timer = setInterval(function(){
         var nodes = zTreeObj.getNodesByFilter(function(node) {
            return !node.zAsync;
         });
         
         if(nodes.length==0){
             clearInterval(zTreeAsyncReady.timer);
             zTreeAsyncReady.timer == null;
             zTreeAsyncReady.done = true;
         }
         
         console.log('没执行完');
         
         if (zTreeAsyncReady.done) {
              f();
         }
     },100);
}

/**
 * 搜索方法
 */
function search(){
    var treeObj = $.fn.zTree.getZTreeObj('zTree');
    var value = $.trim($('#search').val());
    
    if(value == ""){
        var hides = treeObj.getNodesByParam("isHidden", true);    //显示所有隐藏节点
        treeObj.showNodes(hides);
        return;
    }
    
    //查找节点
    var nodes = treeObj.getNodesByParamFuzzy('name', value);
    if(nodes.length==0){
        alert('未搜索到数据!');
        return;
    }
    
    //隐藏所有节点
    var all = treeObj.transformToArray(treeObj.getNodes());
    for (var i = 0; i < all.length; i++) {
        treeObj.hideNode(all[i]);
    }
    
    //展示查找到的节点
    for (var i = 0; i < nodes.length; i++) {
        treeObj.showNode(nodes[i]);//显示查到节点
        var parentNodes = [];
        getParentsNode(nodes[i], parentNodes);
        treeObj.showNodes(parentNodes);    ////显示其所有父节点
        treeObj.expandAll(true);//展开所有查询到的内容
    }
}

/**
 * 获取所有节点的父节点
 */
function getParentsNode(node, array){
    var parentNode = node.getParentNode();
    if(parentNode!=null){
        array.push(parentNode);
        getParentsNode(parentNode, array);
    }
    return;
}

</script>
</html>

 

后台异步加载节点的代码:仅仅是模拟使用的;很简单的模拟:

package com.cy.controller;

import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.test.model.Node;

@Controller
public class ZtreeController {
    @RequestMapping("/asyncGetNodes")
    @ResponseBody
    public List<Node> asyncGetNodes(String id, String pid, String name) throws Exception{
        List<Node> nodeList = new ArrayList<Node>();
        if(id==null){
            nodeList.add(new Node("1","0","硬件规格","false","true"));
            nodeList.add(new Node("2","0","软件规格","false","true"));
            return nodeList;
        }
        
        if(id.equals("1")){
            nodeList.add(new Node("10","1","单板","false","true"));
            nodeList.add(new Node("11","1","子卡","false","true"));
            nodeList.add(new Node("12","1","设备","false","true"));
        }else if(id.equals("2")){
            nodeList.add(new Node("20","2","java","false","true"));
            nodeList.add(new Node("21","2","jscript","false","true"));
            nodeList.add(new Node("22","2","php","false","true"));
        }else if(id.equals("10")){
            nodeList.add(new Node("100",id,"单板_00","false","true"));
            nodeList.add(new Node("101",id,"单板_00","false","false"));
        }else if(id.equals("100")){
            nodeList.add(new Node("1000",id,"单板_00_00","false","false"));
        }
        
        Thread.sleep(1000);
        return nodeList;
    }
}
View Code

 

如果有更好的ztree异步搜索的方法,欢迎大伙留言。不胜感激!!

 

效果:

posted on 2018-03-28 01:39  有点懒惰的大青年  阅读(822)  评论(0编辑  收藏  举报