首页 > 代码库 > 【JSTREE】 jstree-初始化时默认选中根节点

【JSTREE】 jstree-初始化时默认选中根节点

技术分享
var contacttree = $(‘#contact-org‘).jstree({  
    "core" : {  
        "animation" : false,  
        "multiple" : false,  
        "check_callback" : true,  
        "themes" : {  
            "icons" : true,  
            "dots" : false  
        },  
        "data" : {  
            "dataType": ‘json‘,  
            "url":function(node){  
                return node.id==="#" ?  
                    ctxPath + "/v-contact?queryOrg":ctxPath + "/v-contact?queryOrg";  
            },  
            "data":function(node){  
                return {"id" : node.id};  
            }  
        }  
    }).on(‘loaded.jstree‘, function(e, data){  
    var inst = data.instance;  
    var obj = inst.get_node(e.target.firstChild.firstChild.lastChild);  
      
    inst.select_node(obj);  
});    
View Code

通过 loaded.jstree 这个动作,当tree加载完毕时,获取树的根节点对象;

调用select_node方法,选择根节点。

 

进阶:

赋上get_node的说明(可以传入ID来获取节点,但是上述情况的话,必须得知道哪个是根节点):

get_node();

 

$("#demo")

.bind("loaded.jstree", function (e, data) {

                    data.inst.open_all(-1); // -1 opens all nodes in the container

                    })

.jstree({

                //  你的jstree的设置

            })

 

技术分享
public Object Menu(String roleId, HttpServletRequest req) {
        List<SysMenu> list = menuService.query(Cnd.orderBy().asc("location").asc("path"));
        List<SysMenu> datas = roleService.getDatas();
        List<NutMap> menus = new ArrayList<>();
        List<SysMenu> roleMenus = roleService.getMenusAndButtons(roleId);//当前角色的权限
        for (SysMenu menu : list) {
            NutMap map = new NutMap();
            for (SysMenu bt : datas) {
                if (menu.getPath().equals(bt.getPath().substring(0, bt.getPath().length() - 4))) {
                    menu.setHasChildren(true);
                    break;
                }
            }
            for(SysMenu rm:roleMenus){
                if (menu.getId().equals(rm.getId())){
                    map.put("state", new State(false,false,true));//是否允许编辑-是否展开-是否选中树节点
                    break;
                }
            }
            map.put("id", menu.getId());
            map.put("text", menu.getName());
            map.put("icon", Strings.sBlank(menu.getIcon()));
            map.put("parent", "".equals(Strings.sNull(menu.getParentId())) ? "#" : menu.getParentId());
            map.put("data", menu.getHref());
            menus.add(map);
        }
        req.setAttribute("menus", Json.toJson(menus));
        return Strings.isBlank(roleId) ? null : roleService.fetch(roleId);
    }
 
public class State {
    private boolean disabled;
    private boolean opened;
    private boolean selected;

    /**
     * 树节点勾选
     * @param disabled  编辑
     * @param opened  是否展开
     * @param selected  是否选中
     */
    public State(boolean disabled,boolean opened,boolean selected){
        this.disabled=disabled;
        this.opened=opened;
        this.selected=selected;

    }

    public boolean isDisabled() {
        return disabled;
    }

    public void setDisabled(boolean disabled) {
        this.disabled = disabled;
    }

    public boolean isOpened() {
        return opened;
    }

    public void setOpened(boolean opened) {
        this.opened = opened;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }
}
 
<header class="header navbar bg-white shadow">
  
</header>
<div class="content-wrap">
    <div class="wrapper">
        <div class="row mb15">
            <div class="col-lg-12">
                <form id="addRoleForm" class="form-horizontal stepy" method="post" action="url">
                    <input type="hidden" id="menuIds" name="menuIds"/>
                    <div class="form-group no-b">
                        <div class="col-s-m-8">
                            <div class="panel">
                                <div class="panel-heading no-b">
                                    <h5>选择<b>菜单</b></h5>
                                </div>
                                <div class="panel-body">
                                    <div id="jsTreeMenu"></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-s-m-4">
                            <div class="panel">
                                <div class="panel-heading no-b">
                                    <h5>菜单<b>描述</b></h5>
                                </div>
                                <div id="menuDescript" class="panel-body">
                                    <div class=‘alert alert-info‘>请勾选每一个需要分配的菜单</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<script language="JavaScript">
    var jsTreeMenu;
    $(function () {
        jsTreeMenu = $("#jsTreeMenu").jstree({
                    plugins: ["wholerow", "checkbox"],
                    core: {
                        data: ${menus!}
                },
                checkbox: {
                    three_state: false,
                    cascade: ‘down‘
        }
    }).on("hover_node.jstree", function (e, data) {
        if (data.node.data)
            $("#menuDescript").text(data.node.data);
    }).on("dehover_node.jstree", function (e, data) {
        $("#menuDescript").html("<div class=‘alert alert-info‘>请勾选每一个需要分配的菜单</div>");//清空菜单描述
    }).bind("loaded.jstree", function (e, data) {
        //立即加载树下所有节点

    });
    });
    function each(node, tree, nodes) {
        var p = tree.get_parent(node);
        if (p.length > 1) {
            if (nodes&&p&&nodes.indexOf(p)<0)
                nodes.push(p);
            each(p, tree, nodes);
        }
    }
    function complete() {
        var tree = $.jstree.reference("#jsTreeMenu");
        var ids = tree.get_selected();
        //查询所选节点的所有父节点
        for (var i = 0; i < ids.length; i++) {
            var node = ids[i];
            each(node, tree, ids);
        }
        if (ids.length > 0) {
            $.post("url", {menuIds: ids.toString(), roleid: ‘${obj.id}‘}, function (data) {
            if (data.code == 0) {
                Toast.success(data.msg);
                setTimeout(function () {
                    $("#goback").trigger("click");
                }, 1000);
            } else {
                Toast.error(data.msg);
            }
        }, "json");
    } else {
        Toast.warning("请先选择菜单!");
    }
    }
</script>
<%}%>
View Code
技术分享
$(function () {  
     $.ajaxSetup({cache:false});  
     $("#tree").tree({  
         data : {  
             type : "json",  
             async : true,  
             opts : {  
                 async : true,  
                 method : "GET",  
                 //向后台发送请求的url或json格式的数据文件  
                 url : "json_data.json"  
             }  
         },  
         root : { attributes : { "id" : "0" }, data : "ROOT", state : "closed"},  
         lang:{  
             loading:"目录加载中……"  
         },  
         ui:{  
             theme_name:‘checkbox‘  
         },  
         callback : {  
             // Make sure static is not used once the tree has loaded for the first time  
             onl oad : function (t) {  
                 t.settings.data.opts.static = false;  
             },  
             beforedata : function (n, t) {  
                 if (n == false)  
                     t.settings.data.opts.static = t.settings.root;  
                 else  
                     return {parent_Id : $(n).attr("id") }  
             },  
             //checkbox树展开之后,设置节点为选中状态  
             onopen_all : function() {  
               var selectedIds = [];  
               for (var i = 0; i < selectedIds.length; i++)  {  
                jQuery.tree.plugins.checkbox.check($("#"+ selectedIds[i]+""));  
               }  
             }  
         },  
         plugins:{  
             checkbox:{}  
         }  
     });  
 });  
View Code

在树return data的时候,对该data先进行处理,追加open和check

// Alternative format of the node (id & parent are required)
{
  id          : "string" // required
  parent      : "string" // required
  text        : "string" // node text
  icon        : "string" // string for custom
  state       : {
    opened    : boolean  // is the node open
    disabled  : boolean  // is the node disabled
    selected  : boolean  // is the node selected
  },
  li_attr     : {}  // attributes for the generated LI node
  a_attr      : {}  // attributes for the generated A node
}

【JSTREE】 jstree-初始化时默认选中根节点