简体   繁体   中英

How do I select the root node in jstree?

I am trying to embed some functionality in my jstree based on whether it is a root node or if it is one of the child nodes. From the jstree documentation and other Stack Overflow posts that I have gone through, I am now able to populate the items correctly, but I am at a roadblock on how to select the root node of the jstree in an "select_node" condition like the following snippet. Is this correct appending the word "root" to select_node? Please advise. (My root item is called "root", if I have to call get_parent() and check how would I pass my root as paramter). Any pointers to proceed would be appreciated.

$(".myjstree").on("select_node.jstree.root", function (e, data){
// do stuff if this is my root node
});

Listening to select_node.jstree.root does not work as intended, as all it does is create an additional namespace for select_node.jstree (see the Event names and namespaces section from http://api.jquery.com/on/ for more information). select_node.jstree.root events are still triggered for all select_node.jstree events.

Instead, you can check whether the root node is selected via the data.selected property in select_node.jstree . You can also interact with it via $('#jstree').jstree(true).get_node('root') like so:

 $('#jstree').jstree({ core: { data: [ { id: 'root', text: 'Root', state: { opened: true }, children: [ { id: 'child-node-1', text: 'Child 1' }, { id: 'child-node-2', text: 'Child 2' } ] } ] } }); $('#jstree').on("changed.jstree", function (e, data) { if (data.selected.length === 1 && data.selected[0] === 'root') { let root_node = $('#jstree').jstree(true).get_node('root'); console.log(root_node); } }); 
 @import "https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css"; 
 <div id="jstree"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM