我能够使用替代JSON格式创建jstree,如下所示:
$('#using_json_2').jstree({ 'core' : { 'data' : [ { "id" : "ajson1","parent" : "#","text" : "Simple root node" },{ "id" : "ajson2","text" : "Root node 2" },{ "id" : "ajson3","parent" : "ajson2","text" : "Child 1" },{ "id" : "ajson4","text" : "Child 2" },] } });
但这是非常静态的.我希望它是动态的;从某种意义上说,行数可以是变量,行属性可以从数组中读取.我不想使用ajax,因为数据已经在数组中可用.
解决方法
如果您希望数据是动态的,可以使用以下代码初始化您的jstree:
$('#jstree').jstree({ 'core': { 'data': arrayCollection } });
其中arrayCollection是一个包含动态数组的变量.例如,您的arrayCollection可能如下所示:
var arrayCollection = [ {"id": "animal","parent": "#","text": "Animals"},{"id": "device","text": "Devices"},{"id": "dog","parent": "animal","text": "Dogs"},{"id": "lion","text": "Lions"},{"id": "mobile","parent": "device","text": "Mobile Phones"},{"id": "lappy","text": "Laptops"},{"id": "daburman","parent": "dog","text": "Dabur Man","icon": "/"},{"id": "Dalmation","text": "Dalmatian",{"id": "african","parent": "lion","text": "African Lion",{"id": "indian","text": "Indian Lion",{"id": "apple","parent": "mobile","text": "Apple IPhone 6",{"id": "samsung","text": "Samsung Note II",{"id": "lenevo","parent": "lappy","text": "Lenevo",{"id": "hp","text": "HP","icon": "/"} ];
最后,您的html文件应如下所示:
<html> <head> <title>JSTree</title> <link rel="stylesheet" href="dist/themes/default/style.css" /> <script src="dist/libs/jquery.js"></script> <script src="dist/jstree.js"></script> <script> $(function() { var arrayCollection = [ {"id": "animal","icon": "/"} ]; $('#jstree').jstree({ 'core': { 'data': arrayCollection } }); }); </script> </head> <body> <div id="jstree"></div> </body> </html>
每当修改arrayCollection时,都必须将arrayCollection重新分配给jstree并以编程方式刷新jstree.