原本以為樹狀結構視覺化應該很簡單,沒想到寫起來這麼難,而且還有移動的判斷也很複雜。最後選擇的方案是使用。jstree 來解決,網站在:https://www.jstree.com/
github: https://github.com/vakata/jstree
官方網站寫的文件,滿少的,直接在 github 的 repo 裡用關鍵字找答案,反而會快一點。
例如:要如何匯出編輯好的樹,在 repo 查詢:export, 在 issue 裡就可以看到答案是使用 get_json()
$('#your_selector').jstree().get_json();另一個介紹滿好的是 wiki:
https://github.com/vakata/jstree/wiki
如何讓 div 可以移動:https://www.w3schools.com/howto/howto_js_draggable.asp
可以移動後,要做的事太多,比較簡單的範例,參考看看:
- https://codepen.io/esironal/pen/JjrRxq
- https://gist.github.com/cadreoneseven/98f006aad4f5f4c81d161d6912fe9a41
仔細一下,用了超多程式碼,而且還做不到細部的移動,例如把某一個孫子節點,搬到 root 下的第一層。光是看到程式碼就暈倒了。
最後還是決定用 jstree.
雖然官方放的範例,是有,但看不懂,反而是其他網站做的文件,比較易懂,例如:
- https://preview.keenthemes.com/html/keen/docs/general/jstree/dragdrop
- https://vikyd.gitbooks.io/jstree/content/plugin.html
直接 copy / past 就可以做出顯示 tree 且有移動功能:

我使用的sample code:
<div id="html1"></div>
<script>
$("#html1").jstree({
	  "core" : {
		"check_callback" : true,
		'data': [{
		             "text": "Parent Node",
	                 "state": {
	                	 "opened": true
	                 },
		             "children": [{
		                 "text": "Initially selected",
		             }, {
		                 "text": "Custom Icon",
		             }, {
		                 "text": "Initially open",
		                 "state": {
		                     "opened": true
		                 },
		                 "children": [
		                     {"text": "Another node"}
		                 ]
		             }, {
		                 "text": "Another Custom Icon",
		             }, {
		                 "text": "Disabled Node"
		             }]
		         },
		         "Another Node"
		     ]
	  },
	  "plugins" : ["dnd", "state", "types"]
	});
</script>create node example:
var parent = '#';
var node = { id:123,text:"Hello world"};
$('#yourtree').jstree('create_node', parent, node, 'last');
Alternative syntax that seems to be working:
$('#yourtree').jstree().create_node(parent, node, 'last');