使用 EasyUI tree 組件加載異步數據(url 模式),要求 **樹初次加載完成即全部展開**,無需用戶手動點擊。
$(function () {
$('#tt').tree({
url: '<%= request.getContextPath() %>/treeInit',
lines: true,
onLoadSuccess: function (node, data) {
var t = $(this);
if (data) {
$(data).each(function (index, d) {
if (this.state === 'closed') {
t.tree('expandAll');
return false; // 跳出 each,避免重複調用
}
});
}
}
});
});
| 屬性/方法 | 作用 |
|---|---|
url | 異步加載數據端點,返回 JSON 陣列,節點含 id,text,state,children。 |
lines: true | 顯示連接線,增強層級可視性。 |
onLoadSuccess(node, data) | 數據加載完成回調。data 為當前層級的節點數組(非整棵樹)。 |
state === 'closed' | 判斷節點是否有子節點且處於折疊狀態(異步模式下初始為 closed)。 |
tree('expandAll') | 遞歸展開所有節點,會觸發後續層級的異步加載並繼續展開。 |
onLoadSuccess 在**每一層**加載完成時都會觸發(根節點、子節點各自觸發)。closed 節點時,才需要展開;否則說明已是葉子節點或已展開。return false 跳出 $.each,避免同一層級重複調用 expandAll。onLoadSuccess: function (node, data) {
if (!node) { // 根節點加載完成
$(this).tree('expand', $(this).tree('getRoot').target); // 僅展開根
}
}
jquery.easyui.min.js 已載入。state 必須為 'open' 或 'closed'(小寫),children 可選。expandAll 會遞歸請求所有層級,數據量大時建議分頁或虛擬滾動。url 返回完整樹結構(含所有 children),則無需 expandAll,直接 animate: true 即可動畫展開。異步樹全展開核心在於:
onLoadSuccess 監聽每層加載 → 檢測 closed 節點 → expandAll() 觸發遞歸加載與展開。
三行核心邏輯,解決「一進頁面就要看全樹」的產品需求。