jstree的简单功能使用

jstree的简单使用

  • jstree实现自定义图标
  • jstree实现拖拽
  • jstree实现拖拽后保留顺序
  • jstree实现点击链接href属性
  • jstree实现增删改
  • jstre实现层级目录,类似doc文档目录
  • jstree展开层级目录
<body>
<div class="lesson-list-div">
    <div id="lesson-list-jstree">
    </div>
</div>

<div class="btn-tpl hidden">
    <div class="btn-group">
        <button class='btn btn-primary create' onclick="CALLBACK.node_create()">增加</button>
        <button class='btn btn-info delete' onclick="CALLBACK.node_rename()">修改</button>
        <button class='btn btn-success rename' onclick="CALLBACK.node_delete()">删除</button>
    </div>
</div>
<div>
    <input type="button" onclick="CALLBACK.save_jstree_data()" value="提交">
</div>

</body>

<script>
    var course_id = "{{ course.id }}";
    var lesson_jstree_list_url = "{% url 'cms_course:api:lesson-jstree-list' %}?course_id="+course_id;
    var lesson_jstree_post_url = "{% url 'cms_course:api:lesson-jstree-change-data' %}";
    var js_data = new Array();

    $(function () {
        CALLBACK.init_jstree()
    });

    CALLBACK = {
        save_jstree_data: function () {
            var order_list = new Array();
            $.each($("#lesson-list-jstree li"), function (k, v) {
                order_list.push(v.getAttribute('id'))
            });

            {#var ref = $("#lesson-list-jstree").jstree(true);#}
            var json_datas = ref._model.data;
            var data = new Array()
            for (var json_data in json_datas) {
                if (json_datas[json_data]['id'] != "#") {
                    var temp_data = json_datas[json_data]["original"];
                    temp_data['id'] = json_datas[json_data]['id'];
                    temp_data['self_id'] = json_datas[json_data]['id'];
                    temp_data['text'] = json_datas[json_data]['text'];
                    temp_data['type'] = json_datas[json_data]['type'];
                    temp_data['parent'] = json_datas[json_data]['parent'];
                    temp_data['course'] = course_id;
                    data.push(temp_data)
                }
            }

            $.post(lesson_jstree_post_url, {
                data: JSON.stringify(data),
                order: order_list.join(","),
                course_id: course_id
            }, function (data) {

                console.log(data);
            }, 'json')
        },

        node_create: function () {

            {#var ref = $("#lesson-list-jstree").jstree(true);#}
            var sel = ref.get_selected();
            if (!sel.length) {
                alert("请先选择一个节点");
                return;
            }
            sel = sel[0];
            sel = ref.create_node(sel);
            if (sel) {
                ref.edit(sel);
            }
        },

        node_rename: function () {
            {#var ref = $("#lesson-list-jstree").jstree(true);#}
            var sel = ref.get_selected();
            if (!sel.length) {
                alert("请先选择一个节点");
                return;
            }
            sel = sel[0];
            ref.edit(sel);
        },

        node_delete: function () {
            {#var ref = $("#lesson-list-jstree").jstree(true);#}
            var sel = ref.get_selected();
            if (!sel.length) {
                alert("请先选择一个节点");
                return;
            }
            sel = sel[0];
            if (ref.get_node(sel).parent == '#') {
                alert("根节点不允许删除");
                return;
            }
            if (ref.get_node(sel).children.length > 0) {
                alert('存在子节点,不可删除');
                return;
            }

            ref.delete_node(sel);
        },

        init_jstree: function () {
            var $tree = $("#lesson-list-jstree").jstree({
                'core': {
                    "check_callback": true,//在对树进行改变时,check_callback是必须设置为true;
                    "data": js_data,
                },
                "types": {
                    "#": {
                        "max_children": 1, // 子目录个数
                        "max_depth": 4,  //层级深度
                        "valid_children": ["default"]
                    },
                    "default": {
                        "icon": "fa fa-folder icon-state-warning icon-lg",
                        "valid_children" : ["default","folder", "file"]
                    },
                    "folder": {
                        "icon": "fa fa-folder icon-state-success jstree-themeicon-custom",
                        "valid_children" : ["file"]
                    },
                    "file": {
                        "icon": "fa fa-file icon-state-warning icon-lg",
                        "valid_children" : [] //文件目录下不可增加目录
                    }
                },
                //plugins-各种jstree的插件引入,展示树的多样性
                "sort": function (a, b) {
                    return this.get_node(a).original.order > this.get_node(b).original.order ? 1 : -1;
                    {#return this.get_type(a) === this.get_type(b) ? (this.get_text(a) > this.get_text(b) ? 1 : -1) : (this.get_type(a) >= this.get_type(b) ? 1 : -1);#}
                },
                "plugins": ["dnd", "wholerow", "types", "unique"]

            });
            ref = $tree.jstree(true);
            $tree.on('hover_node.jstree', function (e, data) {
                //监听鼠标移上事件
                // console.log(data)
                var node = data.node;
                var a_attr = node.a_attr;
                var a_attr_id = a_attr.id;
                var id = node.id;
                if (node.type == 'folder' || node.type == 'default') {
                    $('#' + a_attr_id).css({'background': 'transparent', 'box-shadow': 'none'});
                    var btnTpl = $('.btn-tpl').clone().html();
                    $('#' + a_attr_id).append(btnTpl)
                }
            });
            $tree.on('dehover_node.jstree', function (e, data) {
                //监听鼠标移出事件
                var node = data.node;
                var a_attr = node.a_attr;
                var a_attr_id = a_attr.id
                var id = node.id;
                if (node.parent == "#") { //判断选中是否为父类
                    $('#' + a_attr_id).children('.btn-group').remove();
                } else {
                    $('#' + a_attr_id).children('.btn-group').remove();
                }
            });
            $tree.on('ready.jstree', function (e, data) {
                console.log(data);
                //不能以数字进行id选取 隐藏根节点,传入更节点id
                $("#1").css("visibility", "hidden");
            });

             $tree.on("load_node.jstree", function (e, d) {
             // jstree自定义图标
                    var nodes = d.node.children_d;
                    for (var i in nodes) {
                        var node = d.instance.get_node(nodes[i]);
                        var _node = node.original;
                        if (_node.lesson == null){
                            d.instance.set_icon(nodes[i], false)
                        }
                        else if (_node.lesson.learning_status == "0") {//未开始
                            d.instance.set_icon(nodes[i], "fa fa-circle-o orangeC")
                        } else if (_node.lesson.learning_status == "1") {//进行中
                            d.instance.set_icon(nodes[i], "{% static 'course/img/learning.png' %}")
                        } else if (_node.lesson.learning_status == "2") {//已完成
                            d.instance.set_icon(nodes[i], "fa fa-circle orangeC")
                        } else {
                            d.instance.set_icon(nodes[i], false)
                        }
                    }
                });

            $.get(lesson_jstree_list_url, {}, function (data) {
                // 刷新jstree的数据
                js_data = data.rows;
                var length = js_data.length;
                var first_count = 1;
                var dic_count = {};
                for (var i = 0; i < length; i++) {
                    if (js_data[i].lesson != null){ // 为jstree添加href属性, 使用activate_node.jstree事件进行链接跳转
                        if (js_data[i].lesson.lesson_type == '2' || js_data[i].lesson.lesson_type == '3'){
                            var testpaper_id = js_data[i].lesson.testpaper_id;
                            if (/^\d+$/.test(testpaper_id)){
                                js_data[i].a_attr = {"href": "{% url 'practice_capability:exam_detail' 0 %}".replace(0, testpaper_id)}
                            }
                        }else {
                            js_data[i].a_attr = {"href": "{% url 'course:markdown_new'%}"+"?course_id="+course_id+"&lesson_id="+js_data[i].lesson.lesson_id}
                        }
                    }
                    if (js_data[i].parent != "#"){  // 设置自动添加文件目录类似doc层级目录
                        // 一级文件 和一级文件夹, 一级文件不做处理
                        if (js_data[i].parents.length == 2 && js_data[i].type != "file") {// 一级文件夹
                            js_data[i].text = gettext("x_NO_nbsp") + first_count + gettext("x_chapter_nbsp") + js_data[i].text;
                            dic_count[js_data[i].id] = first_count;
                            dic_count[js_data[i].id + '_count'] = 1;
                            first_count += 1;
                        }else if (js_data[i].parents.length == 3 || js_data[i].parents.length == 4){ // 二级文件夹 和二级文件
                            var chapter_order = dic_count[js_data[i].parents[0]]; // 一级文件夹order
                            var current_number = dic_count[js_data[i].parents[0] + "_count"];
                            if (js_data[i].type == "file"){
                                var lessonType = lesson_typ_dic[js_data[i].lesson.lesson_type] + " - ";
                                js_data[i].text = chapter_order + "." + current_number + "&nbsp;&nbsp;" + lessonType + js_data[i].text;
                            }else {
                                js_data[i].text = chapter_order + "." + current_number + "&nbsp;&nbsp;" + js_data[i].text;
                            }
                            dic_count[js_data[i].parents[0] + "_count"] += 1;
                            if (js_data[i].type != "file"){ // 二级文件夹多余的操作
                                dic_count[js_data[i].id] = chapter_order + "." + current_number;
                                dic_count[js_data[i].id + '_count'] = 1;
                            }
                        }else if (js_data[i].parents.length == 5){
                            var chapter_order = dic_count[js_data[i].parents[0]]; // 三级文件夹order
                            var current_number = dic_count[js_data[i].parents[0] + "_count"];
                            if (js_data[i].type == "file"){
                                var lessonType = lesson_typ_dic[js_data[i].lesson.lesson_type] + " - ";
                                js_data[i].text = chapter_order + "." + current_number + "&nbsp;&nbsp;&nbsp;" + lessonType + js_data[i].text;
                            }else {
                                js_data[i].text = chapter_order + "." + current_number + "&nbsp;&nbsp;&nbsp;" + js_data[i].text;
                            }
                            dic_count[js_data[i].parents[0] + "_count"] += 1;
                        }
                    }
                }
                $("#lesson-list-jstree").jstree(true).settings.core.data = js_data;
                $("#lesson-list-jstree").jstree(true).refresh();

                $tree.bind("refresh.jstree", function (event, data) {
                    $tree.jstree("open_all");

                });
            });

            $tree.bind("activate_node.jstree", function (obj, e) {
                var currentNode = e.node;
                if (currentNode.a_attr.href != '#') {  //点击节点进行链接跳转
                        var url = currentNode.a_attr.href;
                        window.open(url, "_self");
                    }
            });
            $tree.bind("move_node.jstree", function (e, data, pos) {
            });
            $tree.on("changed.jstree", function (e, data) {
                console.log('chagne')
            });
            $(document).on('dnd_stop.vakata', function (e, data) { //监听dnd结束事件
                console.log('stop');
                return false
            });
            $(document).on('dnd_start.vakata', function (e, data) { //监听dnd开始事件
                console.log('Started');
            });
            $(document).on('dnd_move.vakata', function (e, data) { //监听dnd移动事件
            });
        }
    }

jstree展开所有层级目录:

jstree打开节点的所有方法:
$("td#modelXML").jstree("open_all","#nodeID");

$(document).ready(function() {
    var tree = $('#jstree');
    tree.bind('loaded.jstree', function(event, data) {
        data.instance.open_all();   
    });
    tree.jstree({});
});

var tree = $("td#modelXML")
    .bind("loaded.jstree", function (e, data) {
        data.inst.open_all(-1); // -1 opens all nodes in the container
    })
    .jstree({ /* your jsTree options as normal */ });

如果你刷新它,然后要再次打开的所有节点,您必须使用 ︰

    tree.bind("refresh.jstree", function (event, data) {
        tree.jstree("open_all");
    });
 var tree = $("#id-or-selector-for-my-tree-element");
    tree.bind("loaded.jstree", function (event, data) {
        tree.jstree("open_all");
    });
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 黑客帝国 设计师:白松林 返回首页