当我单击子节点时,如何在jstree
中获取所有父节点的节点数据
假设我有一个jstree
,如下所示:
观察::当我选择File 2
时,我应该获得所有父节点数据,即根节点2 --->子节点2 --->文件2
$('#using_json_2').jstree({ 'core' : {
'data' : [
{ "id" : "ajson1", "parent" : "#", "text" : "Simple root node", "date":"2018"},
{ "id" : "ajson2", "parent" : "#", "text" : "Root node 2", "date":"2018"},
{ "id" : "ajson3", "parent" : "ajson2", "text" : "Child 1", "date":"12" },
{ "id" : "ajson4", "parent" : "ajson2", "text" : "Child 2", "date":"12" },
{ "id" : "ajson5", "parent" : "ajson4", "text" : "File 1", "date":"12","children": false,"icon":"fa fa-file-o" },
{ "id" : "ajson6", "parent" : "ajson4", "text" : "File 2", "date":"12","children": false,"icon":"fa fa-file-o" }
]
} });
<link href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<div id="using_json_2"></div>
预期输出:(当我选择节点File 2
时)
var allParentsNode = [
{ "id" : "ajson2", "parent" : "#", "text" : "Root node 2"},
{ "id" : "ajson4", "parent" : "ajson2", "text" : "Child 2" },
{ "id" : "ajson6", "parent" : "ajson4", "text" : "File 2", "children": false,"icon":"fa fa-file-o" }]
答案 0 :(得分:0)
在docs中,您可以看到选择一个节点时触发了changed.jstree
事件。而且,您可以使用get_selected
和get_path
方法来执行所需的操作:
// Make it a variable so you can access it later
var treeData = [
{ "id" : "ajson1", "parent" : "#", "text" : "Simple root node", "date":"2018"},
{ "id" : "ajson2", "parent" : "#", "text" : "Root node 2", "date":"2018"},
{ "id" : "ajson3", "parent" : "ajson2", "text" : "Child 1", "date":"12" },
{ "id" : "ajson4", "parent" : "ajson2", "text" : "Child 2", "date":"12" },
{ "id" : "ajson5", "parent" : "ajson4", "text" : "File 1", "date":"12","children": false,"icon":"fa fa-file-o" },
{ "id" : "ajson6", "parent" : "ajson4", "text" : "File 2", "date":"12","children": false,"icon":"fa fa-file-o" }
];
var myTree = $('#using_json_2').jstree({ 'core' : {
'data' : treeData // Use it here
}});
myTree.on('changed.jstree', function(e, data) {
var selected = data.instance.get_selected(),
// Get the path (array of IDs, since we pass true)
path = data.instance.get_path(selected, null, true),
// Use `map` to retrieve all nodes
node_path = path.map(function(id) {
return treeData.find(function(node) { return node.id === id; });
});
console.log(node_path);
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<div id="using_json_2"></div>