組織架構、商品分類、地區選單、權限樹——只要資料有父子關係,就需要一顆樹。傳統做法是用 table 拼湊,或用 setTimeout 延後載入子節點。本文示範如何以純 div 與 CSS 建立巢狀結構,再用 jQuery 處理展開收合,讓同一套程式碼支援任意深度。
常見兩種表示法:扁平清單(每筆有 id 與 parentId)或 Already 巢狀(每個節點帶 children 陣列)。後端多回傳扁平資料,前端再組樹:
const flat = [
{ id: 1, pid: 0, name: '台灣' },
{ id: 2, pid: 1, name: '台北市' },
{ id: 3, pid: 2, name: '大安區' },
{ id: 4, pid: 1, name: '新竹縣' }
];
function buildTree(list, pid = 0) {
return list
.filter(item => item.pid === pid)
.map(item => ({ ...item, children: buildTree(list, item.id) }));
}
用巢狀 div 加上縮排線條,比 ul/li 更容易完全掌控樣式:
<style>
.tree, .tree .children { list-style: none; }
.tree-node { margin-left: 14px; position: relative; }
.tree-node::before { /* 階層連接線 */
content: ''; position: absolute; left: -10px; top: 0;
bottom: 0; width: 1px; background: #dcdfe6;
}
.tree-label {
display: flex; align-items: center; gap: 6px;
padding: 4px 8px; cursor: pointer; border-radius: 4px;
}
.tree-label:hover { background: #f2f6fc; }
.tree-node.is-active > .tree-label {
background: #409eff; color: #fff;
}
.children { display: none; }
.tree-node.is-open > .children { display: block; }
.toggle { width: 12px; text-align: center; user-select: none; }
</style>
<div class="tree" id="tree"></div>
function render(nodes, container) {
const frag = document.createDocumentFragment();
nodes.forEach(node => {
const hasChild = node.children && node.children.length;
const li = document.createElement('div');
li.className = 'tree-node';
li.dataset.id = node.id;
li.innerHTML =
'<div class="tree-label">' +
'<span class="toggle">' + (hasChild ? '▸' : '') + '</span>' +
'<span class="name">' + escapeHtml(node.name) + '</span>' +
'</div>';
if (hasChild) {
const box = document.createElement('div');
box.className = 'children';
li.appendChild(box);
render(node.children, box);
}
frag.appendChild(li);
});
container.appendChild(frag);
}
render(buildTree(flat), document.getElementById('tree'));
動態產生的節點無法用一般方式直接綁定事件,改用事件委派掛在容器上,一次搞定所有層級:
$('#tree').on('click', '.toggle', function (e) {
e.stopPropagation();
const node = $(this).closest('.tree-node');
node.toggleClass('is-open');
$(this).text(node.hasClass('is-open') ? '▾' : '▸');
});
$('#tree').on('click', '.name', function () {
$('#tree .tree-node').removeClass('is-active');
$(this).closest('.tree-node').addClass('is-active');
console.log('選取節點 id =', $(this).closest('.tree-node').data('id'));
});
// 全部展開 / 收起
$('#expandAll').on('click', () => {
$('.tree-node').addClass('is-open').children('.toggle').text('▾');
});
$('#collapseAll').on('click', () => {
$('.tree-node').removeClass('is-open').children('.toggle').text('▸');
});
「無限層級」的重點不在寫出多深的迴圈,而在三件事:資料要先正化成樹、渲染要遞迴、事件要委派。這三點做對,深度就不再是你需要擔心的問題。