![](/img/trans.png)
[英]How do I programmatically select a node in jsTree and open all parents
[英]How to get all parents node data when clicked/expanded in jstree
当我单击子节点时如何在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" }]
在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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.