问题
I'm trying to use jstree and let one node and all its parent be opened when the page is opened. Here is the html code I used to test.
<div id="treeTask">
<ul>
<li id="node_37"><a href="#">TEST1</a>
<ul>
<li id="node_38"><a href="#">TEST2</a></li>
<li id="node_39"><a href="#">TEST3</a></li>
</ul>
</li>
</ul>
<ul>
<li id="node_3"><a href="#">TEST1</a>
<ul>
<li id="node_4"><a href="#">TEST2</a></li>
<li id="node_6"><a href="#">TEST3</a></li>
</ul>
</li>
</ul>
</div>
And here is the call to initialize jstree and open the node.
$(function () {
$("#treeTask").jstree();
$("#treeTask").bind("ready.jstree", function (event, data) {
$("#treeTask").jstree("open_node", $("#node_4"));
if((data.inst._get_parent(data.rslt.obj)).length) {
data.inst._get_parent(data.rslt.obj).open_node(this, false);
}
});
});
I have been manipulating the code for a while, but could not make it work. I would really appreciate if anyone can help.
Thanks so much!
回答1:
You can use the built-in _open_to
function:
http://www.jstree.com/api/#/?q=open_to&f=_open_to%28obj%29
$("#treeTask").jstree().bind('ready.jstree', function (event, data) {
data.instance._open_to('node_4');
});
回答2:
Based on @maddin solution, I've updated it to support any number of parent levels.
jsFiddle
$("#treeTask").jstree().bind('ready.jstree', function (event, data) {
$("#treeTask").jstree('open_node', 'node_4', function(e,d) {
for (var i = 0; i < e.parents.length; i++) {
$("#treeTask").jstree('open_node', e.parents[i]);
};
});
});
It should be noted that if a node is selected, all its parents will be opened automatically. This would be somewhat equivalent to the above:
$("#treeTask").jstree().bind('ready.jstree', function (event, data) {
$("#treeTask").jstree('select_node', 'node_4');
});
回答3:
Maybe this is an Solution for your problem:
fiddle
$("#treeTask").jstree().bind('ready.jstree', function (event, data) {
$("#treeTask").jstree('open_node', 'node_4', function(e,d) {
if(e.parents.length){
$("#treeTask").jstree('open_node', e.parent);
};
});
});
来源:https://stackoverflow.com/questions/27660403/open-one-node-and-all-its-parents-using-jstree