티스토리 뷰

WEB/JQuery

JSON 동적 트리 탐색기

silverline79 2026. 1. 22. 23:05

<!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>

JSON 동적 트리 탐색기.html
0.00MB

 

※ 해당 내용은 Google Gmini3.0에서 작성되었습니다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG more
«   2026/01   »
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
글 보관함