ztree的使用

在开发中想使用树tree的列表 后来用的是ztree

看过可以使用的有bootstrap treeview ,UI: easyUI, layui, BUI,Jquery UI等等;

ztree的学习源头:

http://www.treejs.cn/v3/main.php#_zTreeInfo

demo和api很丰富, 常用功能足够使用了

我自己的项目中 重要用到了radio和checkout 选项

页面代码:

@extends('layouts.layout')
@section('link')
    <link rel="stylesheet" href="{{ asset('ztree/css/zTreeStyle/zTreeStyle.css')}}">
    <script src="{{asset('layer/layer.js')}}"></script>
    <script type="text/javascript" src="{{ asset('ztree/js/jquery.ztree.core.min.js')}}"></script>
    <script type="text/javascript" src="{{ asset('ztree/js/jquery.ztree.excheck.min.js')}}"></script>
@endsection
@section('content')
    <SCRIPT type="text/javascript">
        $(function () {
            var setting = {
                view: {
                    fontCss: function (treeId, treeNode) {
                        return (!!treeNode.highlight) ? {color: "#F08080", "font-weight": "bold"} : {
                            color: "black", "font-weight": "normal"
                        };
                    }
                },
                check: {
                    enable: true,
                    chkboxType: { "Y": "ps", "N": "ps" },
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                }
            };
            var channel = {!! $channel !!};
            var childrentwo = [];
            $.each(channel, function (i, n) {
                childrentwo.push({id: n.channel_id,name:n.name})
            })
            var zNodes =[
                {name:'渠道树',children:
                childrentwo
                },
            ];

            var checkoutObj = $.fn.zTree.init($("#zcheckout"), setting, zNodes);
            checkoutObj.expandAll(true);
//            console.log(checkoutObj);

            var settingone = {
                check: {
                    enable: true,
                    chkStyle: "radio",
                    radioType: "level"
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback : {
                    onCheck: onCheckone,
                }
            };
            function onCheckone(e, treeId, treeNode) {
//                console.log(treeNode.id);
                var url = '/reportSet/getChannel';
                var data = {userid: treeNode.id};
                $.ajax({
                    type:"get",
                    url: url,
                    data:data,
                    dataType:"json",
                    success:function(data){
//                        console.log(data.res);
                        checkoutObj.checkAllNodes(false); // 先清除所有节点
                        var chinnels = [];
                        $.each(data.res, function (i, n) {
                            chinnels.push({id: n.channel_id,name:n.name})
                        })

                        $.each(chinnels, function (i, n) {
                            var node = checkoutObj.getNodeByParam("id", n.id, null);
                            checkoutObj.selectNode(node);
                            checkoutObj.checkNode(node, true, true);
                            checkoutObj.updateNode(node);
                        })
                        layer.msg('获取渠道成功', {icon: 1, zIndex: 666,});
                    }
                });
            }

            //获取当前选中的节点
            function  getCheckedNode(){
                var nodes = zTree.getCheckedNodes(true);
            }
            var user = {!! $user !!};
            var childrenone = [];
            $.each(user, function (i, n) {
                childrenone.push({id: n.id, name:n.name})
            })
            var zNodesone = [
                {name:'用户树',children:
                childrenone
                },
            ];

            var codeone;
            function setCheckone() {
                var type = $("#level").attr("checked")? "level":"all";
                settingone.check.radioType = type;
                showCodeone('setting.check.radioType = "' + type + '";');
                var radioObj = $.fn.zTree.init($("#zradio"), settingone, zNodesone);
                radioObj.expandAll(true);
            }
            function showCodeone(str) {
                if (!codeone) codeone = $("#code");
                codeone.empty();
                codeone.append("<li>"+str+"</li>");
            }

            setCheckone();
            $("#level").bind("change", setCheckone);
            $("#all").bind("change", setCheckone);


            // 点击提交按钮 去更新渠道
            var updateChannel = function () {
                var userid = ''; // 用户id
                var radioObj = $.fn.zTree.getZTreeObj("zradio");
                var radionodes = radioObj.getNodesByParam("checked", true, null);
                $.each(radionodes, function (i, n) {
//                    console.log(n.id);
                    userid = n.id;
                })
//                console.log(userid);
                var checkoutObj = $.fn.zTree.getZTreeObj("zcheckout");
                var checkoutnodes = checkoutObj.getCheckedNodes(true);
                checkoutnodes.shift(); // 去除首个元素 渠道树
                var channel = {}; // 选中的渠道id name
                $.each(checkoutnodes, function (i, n) {
//                    console.log(n.id);
                    channel[i] = {id: n.id, name: n.name};
                })
//                console.log(channel);
//                console.log(radionodes);
//                console.log(checkoutnodes);
                if ($.isEmptyObject(channel)) {
                    layer.msg('请选择一些渠道', {icon: 2, zIndex: 66,});
                } else {
                    var url = '/reportSet/update';
                    var data = {
                        userid: userid,
                        channel: channel
                    }
//                    console.log(data);
                    $.ajax({
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        type:"POST",
                        url: url,
                        data:data,
                        dataType:"json",
                        success:function(data){
                            if(data.tip == 1) {
                                layer.msg('更新成功', {icon: 1, zIndex: 666,});
                            } else {
                                layer.msg('更新失败', {icon: 2, zIndex: 666,});
                            }
                        }
                    });
                }
            }
            // 点击用户 去获取渠道
            $('#bt').click(function () {
                layer.confirm('确定要提交吗?', {
                    btn: ['确认','取消'] //按钮
                }, function(){
                    updateChannel();
                })
            });
            var oldNodes = [];
            // 渠道的模糊搜索
            $('#search').click(function () {
                var input = $('#search_content').val();

                var nodes = checkoutObj.getNodesByParamFuzzy("name", input, null);
//                console.log(nodes);


                function searchNode () {
                    var text = $('#search_content').val();
                    if (text == "") {
                        return;
                    }
                    var treeObj = $.fn.zTree.getZTreeObj('zcheckout');
                    updateNodes(false);
                    oldNodes = treeObj.getNodesByParamFuzzy("name", text, null);
                    updateNodes(true);
                }

                function updateNodes (flag) {
                    //遍历搜索高亮显示
                    var treeObj = $.fn.zTree.getZTreeObj("zcheckout");
                    for (var i = 0, l = oldNodes.length; i < l; i++) {
                        oldNodes[i].highlight = flag;
                        treeObj.updateNode(oldNodes[i]);
                        treeObj.expandNode(oldNodes[i].getParentNode(), flag, null, null, false);
                    }
                }
                searchNode();
            })

        })
    </SCRIPT>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <div class="content_wrap">
        <div class="zTreeDemoBackground left" style="position: relative">
            <ul id="zradio" class="ztree" style="width: 40%; height:850px; float: left;overflow:auto;" ></ul>
            <div style="float: left;width: 40%; height:850px; overflow:auto;">
                <input type="text" id="search_content"><button id="search">搜索</button>
                <ul id="zcheckout" class="ztree" ></ul>
            </div>
        </div>
    </div>
    <button type="button" id="bt" data-toggle="tooltip" title="提交" class="btn btn-primary" style="position: absolute; right: 20%; bottom: 5%">
        提交
    </button>

@endsection

radio 部分

var settingone = {
                check: {
                    enable: true,
                    chkStyle: "radio",
                    radioType: "level"
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback : {
                    onCheck: onCheckone, // 选中radio后触发的事件
                }
            };
            function onCheckone(e, treeId, treeNode) {
//                console.log(treeNode.id);
                var url = '/reportSet/getChannel';
                var data = {userid: treeNode.id};
                $.ajax({
                    type:"get",
                    url: url,
                    data:data,
                    dataType:"json",
                    success:function(data){
//                        console.log(data.res);
                        checkoutObj.checkAllNodes(false); // 先清除所有节点
                        var chinnels = [];
                        $.each(data.res, function (i, n) {
                            chinnels.push({id: n.channel_id,name:n.name})
                        })

                        $.each(chinnels, function (i, n) {
                            var node = checkoutObj.getNodeByParam("id", n.id, null);
                            checkoutObj.selectNode(node);
                            checkoutObj.checkNode(node, true, true);
                            checkoutObj.updateNode(node);
                        })
                        layer.msg('获取渠道成功', {icon: 1, zIndex: 666,});
                    }
                });
            }

            //获取当前选中的节点
            function  getCheckedNode(){
                var nodes = zTree.getCheckedNodes(true); // 获取当前选中的节点
            }
            var user = {!! $user !!};
            var childrenone = [];
            $.each(user, function (i, n) {
                childrenone.push({id: n.id, name:n.name})
            })
            var zNodesone = [
                {name:'用户树',children:
                childrenone
                },
            ];

            var codeone;
            function setCheckone() {
                var type = $("#level").attr("checked")? "level":"all";
                settingone.check.radioType = type;
                showCodeone('setting.check.radioType = "' + type + '";');
                var radioObj = $.fn.zTree.init($("#zradio"), settingone, zNodesone);
                radioObj.expandAll(true);
            }
            function showCodeone(str) {
                if (!codeone) codeone = $("#code");
                codeone.empty();
                codeone.append("<li>"+str+"</li>");
            }

            setCheckone();
            $("#level").bind("change", setCheckone);
            $("#all").bind("change", setCheckone);

checkout部分

$(function () {
            var setting = {
                view: {
                    fontCss: function (treeId, treeNode) {
                        return (!!treeNode.highlight) ? {color: "#F08080", "font-weight": "bold"} : {
                            color: "black", "font-weight": "normal"
                        };
                    }
                },
                check: {
                    enable: true,
                    chkboxType: { "Y": "ps", "N": "ps" },
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                }
            };
            var channel = {!! $channel !!};
            var childrentwo = [];
            $.each(channel, function (i, n) {
                childrentwo.push({id: n.channel_id,name:n.name})
            })
            var zNodes =[
                {name:'渠道树',children:
                childrentwo
                },
            ];

            var checkoutObj = $.fn.zTree.init($("#zcheckout"), setting, zNodes);
            checkoutObj.expandAll(true);

最后由于数据太多 自己做了个简单的模糊搜索高亮显示 

学习源头:https://blog.csdn.net/qq_34149805/article/details/78223922?locationNum=8&fps=1


主要用到了fontCss属性,设置通过每个树节点的highlight属性来判断其是否高亮。


然后我们定义一个全局变量(这样就可以获取上次的查询结果以消除上次查询的高亮)oldNodes来存储查询到的树节点。


var
oldNodes = []; // 渠道的模糊搜索 $('#search').click(function () { var input = $('#search_content').val(); var nodes = checkoutObj.getNodesByParamFuzzy("name", input, null); // console.log(nodes); function searchNode () { var text = $('#search_content').val(); if (text == "") { return; } var treeObj = $.fn.zTree.getZTreeObj('zcheckout'); updateNodes(false); oldNodes = treeObj.getNodesByParamFuzzy("name", text, null); updateNodes(true); } function updateNodes (flag) { //遍历搜索高亮显示 var treeObj = $.fn.zTree.getZTreeObj("zcheckout"); for (var i = 0, l = oldNodes.length; i < l; i++) { oldNodes[i].highlight = flag; treeObj.updateNode(oldNodes[i]); treeObj.expandNode(oldNodes[i].getParentNode(), flag, null, null, false); } } searchNode(); })

var setting = {
view: {
fontCss: function (treeId, treeNode) {
return (!!treeNode.highlight) ? {color: "#F08080", "font-weight": "bold"} : {
color: "black", "font-weight": "normal" //设置颜色
};
}
},
check: {
enable: true,
chkboxType: { "Y": "ps", "N": "ps" },
},
data: {
simpleData: {
enable: true
}
}
};
 

 

posted @ 2018-05-07 20:22  段佳伟  阅读(1619)  评论(0编辑  收藏  举报