티스토리 뷰

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>JSON 동적 트리 탐색기</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://unpkg.com/hangul-js"></script>
<style>
/* (스타일은 이전과 동일하므로 핵심만 유지) */
body { font-family: 'Malgun Gothic', sans-serif; padding: 20px; }
.tree-container { background: #fff; width: 480px; margin: 0 auto; padding: 30px; border-radius: 15px; box-shadow: 0 10px 30px rgba(0,0,0,0.08); }
.control-btns { display: flex; gap: 5px; margin-bottom: 10px; justify-content: flex-end; }
.btn { padding: 6px 12px; font-size: 12px; cursor: pointer; border: 1px solid #ddd; border-radius: 4px; }
.search-box input { width: 100%; padding: 12px; margin-bottom: 20px; border: 1px solid #e0e0e0; border-radius: 8px; box-sizing: border-box; }
ul.tree, ul.tree ul { list-style: none; padding-left: 20px; }
.folder, .file { padding: 5px 10px; cursor: pointer; border-radius: 4px; display: inline-block; }
.folder.active + ul { display: block; }
.folder + ul { display: none; } /* 처음엔 닫아두거나 JS에서 open */
.highlight { background-color: #ffeaa7 !important; color: #d63031; font-weight: bold; }
#no-result { display: none; text-align: center; color: #999; }
</style>
</head>
<body>
<div class="tree-container">
<h2>📂 JSON 데이터 탐색기</h2>
<div class="control-btns">
<button id="btn-expand" class="btn">전체 열기 +</button>
<button id="btn-collapse" class="btn">전체 닫기 -</button>
</div>
<div class="search-box">
<input type="text" id="tree-search" placeholder="초성 또는 단어 검색...">
</div>
<div id="no-result">일치하는 항목이 없습니다.</div>
<ul class="tree" id="main-tree"></ul>
</div>
<script>
$(document).ready(function() {
// 1. JSON 데이터를 바탕으로 HTML을 만드는 '재귀 함수'
function createTree(data) {
let html = "";
data.forEach(item => {
if (item.type === "folder") {
html += `<li>
<div class="folder">📂 ${item.name}</div>
<ul>${createTree(item.children)}</ul>
</li>`;
} else {
html += `<li class="file">📄 ${item.name}</li>`;
}
});
return html;
}
// 2. 가상의 JSON 데이터 (실제로는 $.getJSON('url', ...)로 가져옵니다)
const jsonData = [
{
"name": "프로젝트",
"type": "folder",
"children": [
{
"name": "기획단계",
"type": "folder",
"children": [
{ "name": "결산보고서.pdf", "type": "file" },
{ "name": "사업계획서.docx", "type": "file" }
]
},
{ "name": "일정표.hwp", "type": "file" }
]
},
{ "name": "회사규정.pdf", "type": "file" }
];
// 3. 트리 생성 및 초기화
const treeHtml = createTree(jsonData);
$('#main-tree').html(treeHtml);
// 초기 상태: 전체 열기
$('.folder').addClass('active').next('ul').show();
// --- 이벤트 로직 (열기/닫기/검색)은 이전과 동일하게 작동 ---
$(document).on('click', '.folder', function() {
$(this).next('ul').slideToggle(200);
$(this).toggleClass('active');
});
$('#btn-expand').on('click', function() {
$('.folder').addClass('active').next('ul').slideDown(200);
});
$('#btn-collapse').on('click', function() {
$('.folder').removeClass('active').next('ul').slideUp(200);
});
$('#tree-search').on('input', function() {
const query = $(this).val().trim().toLowerCase();
const $allLi = $('#main-tree li');
const $noResult = $('#no-result');
$('.folder, .file').removeClass('highlight');
if (!query) { $allLi.show(); $noResult.hide(); return; }
$allLi.hide();
let hasVisibleItem = false;
$allLi.each(function() {
const text = $(this).children('.folder, .file').text();
if (Hangul.search(text.toLowerCase(), query) !== -1) {
$(this).show().parents('li').show();
$(this).parents('ul').show().prev('.folder').addClass('active');
$(this).children('.folder, .file').addClass('highlight');
hasVisibleItem = true;
}
});
hasVisibleItem ? $noResult.hide() : $noResult.show();
});
});
</script>
</body>
</html>
※ 해당 내용은 Google Gmini3.0에서 작성되었습니다.
'WEB > JQuery' 카테고리의 다른 글
| 인사 관리 시스템 - 검색 제어 강화 (0) | 2026.01.22 |
|---|---|
| 부서 및 사용자 관리 트리 탐색기 (0) | 2026.01.22 |
| API 데이터 호출 및 트리 생성 로직 (0) | 2026.01.22 |
| 전체 열기/닫기 & 동적 트리 통합 코드 (0) | 2026.01.22 |
| 상세 클릭포함 트리메뉴 (0) | 2026.01.22 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- jdk #jre
- 연명의료결정제도 #사전연명의료의향서 #사전연명의료의향서등록기관 #광주사전연명의료의향서
- 와이파이증폭기추천 #와이파이설치
- 파비콘 #파비콘 사이트에 적용
- css미디어쿼리 #미디어쿼리 #mediaquery
- jQuery #jQuery이미지슬라이드 #이미지슬라이드
- lg그램pro #lg그램 #노트북 #노트북추천 #lg노트북
- sw기술자평균임금 #2025년 sw기술자 평균임금
- 좋은책
- 썬크림 #닥터지썬크림 #내돈내산 #내돈내산썬크림 #썬크림추천 #spf50썬크림 #닥터지메디유브이울트라선
- 정보처리기사 #정보처리기사요약 #정보처리기사요점정리
- ajax
- thymeleaf
- 증폭기 #아이피타임증폭기
- iptime와이파이증폭기 #와이파이증폭기설치
- 바지락칼국수 #월곡동칼국수 #칼국수맛집
- 무료폰트 #무료웹폰트 #한수원한돋움 #한수원한울림 #한울림체 #한돋움체
- echart
- SQL명령어 #SQL
- 자바스크립트 #javascript #math
- 자바스크립트정규표현식
- 자바스크립트countiue
- 파비콘사이즈
- 광주분식 #광주분식맛집 #상추튀김 #상추튀김맛집 #광주상추튀김
- 쇼팬하우어 #좋은책
- 좋은책 #밥프록터 #부의원리
- 테스크탑무선랜카드 #무선랜카드 #아이피타이무선랜카드 #a3000mini #무선랜카드추천
- 탭메뉴자바스크립트
- 자바스크립트break
- // 사진직: 데이터가 없으면 DEFAULT_IMG 사용 const profileSrc = (d.img && d.img !== "") ? d.img : DEFAULT_IMG;('#user-photo').attr('src'
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함

