티스토리 뷰

js

트리구조 jsTree 사용해보기

나뜨루다 2023. 12. 7. 17:42
728x90

jstree :  jQuery 기반으로 트리형식의 구조를 지원해 웹에 출력을 도와주는 라이브러리

 

jstree, jquery 스크립트 및 css 

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>

 

자세한 정보는 소스 주석 참고

 

 

1. node가 loaded 되었을때 실행 - $('#jstree').on('loaded.jstree', function (e, data) { });

2. node가 change 되었을때 실행 - $('#jstree').on('changed.jstree', function (e, data) { });

3. node가 select 되었을때 실행 - $('#jstree').on('select_node.jstree', function (e, data) { });

 

모든 node 열기 : $('#jstree').jstree('open_all');

select_node : 특정 노드 선택하기 - $('#jstree').jstree(true).select_node('특정 id');

create_node : 특정 노드 추가하기 - $('#jstree').jstree(true).create_node... 

delete_node : 특정 노드 삭제하기 - $('#jstree').jstree(true).delete_node('특정 id');

 

<!DOCTYPE html>
<html lang="ko">
<head>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!-- jsTree theme -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<style>
button {
  /* 생략 */
  margin: 0;
  padding: 0.5rem 1rem;

  font-family: "Noto Sans KR", sans-serif;
  font-size: 1rem;
  font-weight: 400;
  text-align: center;
  text-decoration: none;

  display: inline-block;
  width: auto;

  border: none;
  border-radius: 4px;
}

#event_result{
  font-size: 1rem;
  font-weight: 400;
  padding: 0.5rem 1rem;
}
</style>
</head>
<body>
<div id="jstree"></div>
<div id="event_result"></div>
<button id="clickBtn">click event</button>
<button id="btnCreate">create node</button>
<button id='btnDelete'>delete node</button>

<!-- jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<!-- jsTree -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<script>

$(function() {
  // 테스트 겸 json data 생성. 추후 ajax로 변경 할 예정
  // parent : 상위 node의 아이디를 지정하여 부모 관계를정함. parent가 '#'인 경우는 최상위 레벨의 노드를 나타냄.
  // id     : node의 id를 지정
  // text   : node의 이름을 지정
  	var data = [
			    { "id" : "p1", "parent" : "#", "text" : "Parent-1" },
				{ "id" : "p2", "parent" : "#", "text" : "Parent-2" },
				{ "id" : "p3", "parent" : "#", "text" : "Parent-3" },
				{ "id" : "c1", "parent" : "p1", "text" : "Child-1" },
				{ "id" : "c2", "parent" : "p1", "text" : "Child-2" },
				{ "id" : "c3", "parent" : "p1", "text" : "Child-3" },
				{ "id" : "c4", "parent" : "p2", "text" : "Child-4" },
				{ "id" : "c5", "parent" : "p2", "text" : "Child-5" },
				{ "id" : "c6", "parent" : "p3", "text" : "Child-6" },
				{ "id" : "g1", "parent" : "c6", "text" : "Grand-1" },
				{ "id" : "g2", "parent" : "c6", "text" : "Grand-2" },
			];
 
// [ajax 구현일경우]
// 	  $('#jstree').jstree({
// 	    'core': {
// 	      'data': {
// 	       'url': '/url',
// 	        'dataType': 'json'
// 	      }
// 	    }
// 	  });
  
    // 인스턴스를 생성
	// jstree의 node 데이터 가져오기
	$('#jstree').jstree({
	  "core": {
	    "check_callback": true,
	    "data": data
	  },
	}).on('create_node.jstree', function(e, data) {
		console.log('saved');
	});

    
    // 이벤트를 설정
	// btnCreate 버튼 클릭 시 
	$('#btnCreate').click(function() {
	 	console.log("btnCreate");
	 	
		// 부모 임의 생성 테스트 parent는 #임
		$('#jstree').jstree(true).create_node('#', {"id": "p4", "text": "Parent-4"}, "last", function() {
		  console.log('Parent Created');
		});
	
		//자식 임의 생성 테스트 create_node('생성할 노드의 부모 노드', {생성할 노드의 정보}, 순서)
		$('#jstree').jstree(true).create_node('p3', {"id": "c7", "text": "Child 7"}, "last", function() {
		  console.log('Child Created');
		});
	});

	$('#btnDelete').click(function() {
		console.log('btnDelete');
		// 위에서 임시 생성한 부모 p4 삭제
		$('#jstree').jstree(true).delete_node('p4');
	});
	 
	// node loaded 되었을때 함수 
	$('#jstree').on('loaded.jstree', function (e, data) {
		console.log('loaded.jstree');
	  
		// loaded 되었을때 모든 node 열기 
		//$('#jstree').jstree("open_all");
		
		// loaded 되었을때 특정한 node 열기 
		$('#jstree').jstree('open_node', 'p1');
	});

	// node가 change 되었을때 함수
	$('#jstree').on('changed.jstree', function (e, data) {
	  console.log(data.selected);
	    
	    var i,j,r = [];
	    for(i = 0, j = data.selected.length; i < j; i++) {
	      r.push(data.instance.get_node(data.selected[i]).text);
	    }
	    // div에 현재 선택 된 값을 나타내기 위함.
	    $('#event_result').html("* [ selected ] : " + r.join(', '));
	
	  });
	
	// node select 되었을때 함수  
	$('#jstree').on('select_node.jstree', function (e, data) {
	  	console.log("select.jstree");
	});
	
	// clickBtn 버튼 클릭 시 
	$('#clickBtn').on('click',function(){
	    console.log('clickBtn click');
	    
		// clickBtn 버튼 클릭 시 특정 node 선택되게 
		$('#jstree').jstree(true).select_node('c5'); // 버튼 클릭 시 특정 노드 선택되게 (id로)
	});
});

</script>
</body>
</html>

 

 

 

 

참고 : https://www.jstree.com/

참고 : https://github.com/vakata/jstree/blob/master/demo/basic/index.html

참고 : https://www.incodom.kr/jsTree