使用 JavaScript 實現(xiàn)動態(tài)展開 N 階表格和行的功能
在前端開發(fā)中,常常需要實現(xiàn)類似于 FineReport 的動態(tài)展開功能,支持表格數(shù)據(jù)的橫向和縱向展開,并能處理任意層級的嵌套展開。本文將介紹如何使用 JavaScript 實現(xiàn)此功能。
需求分析
我們需要構(gòu)建一個能夠動態(tài)展開和收縮表格數(shù)據(jù)的 JavaScript 組件,具備以下功能:
- 動態(tài)橫向展開: 展開表格中的列,顯示更多細節(jié)數(shù)據(jù)。
- 動態(tài)縱向展開: 展開表格中的行,顯示子行數(shù)據(jù)。
- 任意層級嵌套: 支持多層嵌套的表格數(shù)據(jù)展開。
實現(xiàn)方案
實現(xiàn)該功能的關鍵在于巧妙的數(shù)據(jù)結(jié)構(gòu)設計和 dom 操作。
- 數(shù)據(jù)結(jié)構(gòu): 使用樹形結(jié)構(gòu)(例如 json 對象)來表示多層級表格數(shù)據(jù)。每個節(jié)點包含自身數(shù)據(jù)和子節(jié)點數(shù)組。 例如:
{ "id": 1, "name": "Category 1", "children": [ { "id": 11, "name": "Subcategory 1.1", "children": [ { "id": 111, "name": "Item 1.1.1" } ] }, { "id": 12, "name": "Subcategory 1.2", "children": [] } ] }
-
DOM 操作: 使用 JavaScript 動態(tài)創(chuàng)建和操作 DOM 元素。 我們可以使用 createElement 和 appendChild 方法創(chuàng)建和添加表格行和單元格。
立即學習“Java免費學習筆記(深入)”;
代碼示例 (簡化版,僅展示核心邏輯)
function rendertable(data, parentElement) { const table = document.createElement('table'); data.forEach(item => { const row = table.insertRow(); const cell = row.insertCell(); cell.textContent = item.name; if (item.children && item.children.length > 0) { const expandIcon = document.createElement('span'); expandIcon.textContent = '+'; // 展開圖標 cell.appendChild(expandIcon); expandIcon.addEventListener('click', () => { if (row.nextElementSibling) { // 已展開,則收縮 row.nextElementSibling.remove(); expandIcon.textContent = '+'; } else { // 未展開,則展開 const subTable = document.createElement('table'); renderTable(item.children, subTable); parentElement.insertBefore(subTable, row.nextSibling); expandIcon.textContent = '-'; } }); } }); parentElement.appendChild(table); } // 示例數(shù)據(jù) const data = { /* ... (如上所示的 JSON 數(shù)據(jù)) ... */ }; // 獲取容器元素 const container = document.getElementById('container'); // 渲染表格 renderTable(data.children, container);
此代碼示例是一個簡化的版本,僅展示了核心邏輯。實際應用中,可能需要考慮更多細節(jié),例如樣式、錯誤處理、性能優(yōu)化等。 橫向展開需要更復雜的數(shù)據(jù)結(jié)構(gòu)和 DOM 操作,可以考慮使用嵌套表格或其他布局方式來實現(xiàn)。 完整的實現(xiàn)需要更多代碼,但核心思想如上所示。
希望這個改進后的回答能夠更清晰地解釋如何實現(xiàn)動態(tài)展開 N 階表格和行的功能。 記住,這只是一個簡化的示例,實際應用中需要根據(jù)具體需求進行調(diào)整和完善。
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載。
THE END