jsTree で描画するツリー構造イメージを、ノード名を JSON キー、JSON値は jsTreeデータオブジェクト のIDで、
JSON を作成する。
https://www.jstree.com/
RUNボタンを押したら、とりあえず、JSON を生成してコンソールログ出力する。
HTML
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>sample</title> <link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.5.0/css/all.min.css" rel="stylesheet"> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/> <link href="jstree/themes/default/style.min.css" rel="stylesheet" type="text/css"/> <link href="css/develop.css" rel="stylesheet" type="text/css"/> <script src="https://code.jquery.com/jquery-3.5.1.min.js" type="text/javascript"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/jstree@3.3.11/dist/jstree.min.js" type="text/javascript"></script> <!-- ツリーデータ JSON = jsTree 描画用データ --> <script src="treedata.js" type="text/javascript"></script> <!-- jsTree の描画データ を JSONに変換 --> <script src="sample.js" type="text/javascript"></script> <!-- jsTree 描画 --> <script src="develop-tree.js" type="text/javascript"></script> <style type="text/css"> .tree-div{ border: 1px solid; width: 300px; margin: 10px; } </style> </head> <body> <div id="tree" class="tree-div"></div> <button id="run" type="button">RUN</button> </body> </html>
ツリーデータ JSON = jsTree 描画用データである
treedata.js
window.TREE= [ { "id": "1", "icon": "jstree-notIcon", "text": "A", "children": [ { "id": "11", "icon": "jstree-notIcon", "text": "sub_A1", "children": [] }, { "id": "12", "icon": "jstree-notIcon", "text": "sub_A2", "children": [] }, ] }, { "id": "2", "icon": "jstree-notIcon", "text": "B", "children": [] }, { "id": "3", "icon": "jstree-notIcon", "text": "C", "children": [ { "id": "31", "icon": "jstree-notIcon", "text": "sub_C", "children": [ { "id": "32", "icon": "jstree-notIcon", "text": "sub_CC", "children": [] } ] } ] } ]
jsTree 描画のdevelop-tree.js の一部(長いので省略)、
(treedata.js で、読込んだ window.TREE を jstree() で指定する)
$(function(){ $.jstree.defaults.core.themes.variant = "large"; $.jstree.defaults.core.themes.responsive = true; $('#tree').jstree({ 'plugins': [ 'contextmenu','dnd' ], 'core':{ 'data': window.TREE, 'check_callback' : true, }, "contextmenu":{ "items":function($node){ return {
sample.js の内容、
jsTree描画オブジェクトを JSON にする処理で、
treeToJson関数を定義している。
再帰関数 _tjson() を用意するのがpoint
$(function(){ /** * jsTree data Object to JSON */ var treeToJson = function(treeObj){ var _tjson = function(o, c){ if (c.children.length==0){ return c.id; }else{ c.children.forEach(function(e){ o[e.text] = _tjson({}, e); }); return o; } }; json = {}; treeObj.forEach(function(e){ json[e.text] = _tjson({}, e); }); return json; }; /* ボタン押下で、jsTree のデータObject を JSON にして コンソールログ出力 */ $('#run').click(function(e){ tree = window.TREE; json = treeToJson(tree); console.log(JSON.stringify(json, null, 3)) }); });