使用JavaScript从JSON数据构建动态表格遇到技术难题
JavaScript动态生成表格问题
我在用JavaScript从JSON数据创建动态表格时遇到了困难,尝试多种方法均未达到预期效果,具体尝试内容:
- 遍历JSON数据,动态创建表格行和单元格
- 尝试使用jQuery等JavaScript库简化流程,仍存在问题
- 测试多种JSON数据解析与表格注入方法,均未得到理想结果
现有实现代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dynamic Table</title> <script> const dynamicData = [ { name: "GSW", years: [2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028], wins: [10, 11, 12, 13, 13, 13, 13, 14] }, { name: "LAL", years: [2029, 2030, 2031, 2032, 2033, 2034, 2035], wins: [15, 16, 17, 18, 9, 10, 11] }, { name: "PHX", years: [2000, 2001], wins: [1, 4] } ]; function populateTable() { const tableBody = document.getElementById("data-body"); dynamicData.forEach(team => { let yearChunks = chunkArray(team.years, 6); yearChunks.forEach((chunk, index) => { if (index === 0) { const row1 = document.createElement("tr"); const nameCell1 = document.createElement("td"); nameCell1.textContent = "name"; row1.appendChild(nameCell1); const nameCell2 = document.createElement("td"); nameCell2.setAttribute("colspan", `${chunk.length + 1}`); nameCell2.textContent = team.name; row1.appendChild(nameCell2); tableBody.appendChild(row1); } const row2 = document.createElement("tr"); if (index === 0) { const titleCell = document.createElement("td"); titleCell.textContent = "year"; row2.appendChild(titleCell); } chunk.forEach(year => { const yearCell = document.createElement("td"); yearCell.textContent = year; row2.appendChild(yearCell); }); tableBody.appendChild(row2); const row3 = document.createElement("tr"); if (index === 0) { const winsCell = document.createElement("td"); winsCell.textContent = "wins"; row3.appendChild(winsCell); } chunk.forEach((_, i) => { const winsCell = document.createElement("td"); winsCell.textContent = team.wins[index * 6 + i]; row3.appendChild(winsCell); }); tableBody.appendChild(row3); }); }); } function chunkArray(array, size) { const chunks = []; for (let i = 0; i < array.length; i += size) { chunks.push(array.slice(i, i + size)); } return chunks; } window.onload = populateTable; </script> </head> <body> <table border="1"> <tbody id="data-body"> </tbody> </table> </body> </html>
效果对比
当前生成的表格与预期效果不符:
- 预期效果:表格按规则排版,最多6列,满列自动换行,单个队伍数据不足时用下一队数据补全当前行
- 实际效果:每个队伍单独拆分显示,没有实现跨队伍补全列数的逻辑
期望实现的表格规则
- 表格最多显示6列,满6列则自动换行
- 单个队伍的数据不足以填满当前行时,提取下一个队伍的数据进行补充
- 最后一行允许为空行
更新后的JSON数据示例
[ { "name": "GSW", "year": [ "2021", "2022", "2023", "2024", "2025", "2026", "2027", "2028", "2029", "2030", "2031", "2032", "2033", "2034", "2035" ], "wins": [ 10, 11, 12, 13, 13, 13, 13, 14, 15, 16, 17, 18, 19, 20, 21 ] }, { "name": "LAL", "year": [ "2021", "2022", "2023", "2024", "2025", "2026", "2027", "2028", "2029", "2030", "2031", "2032", "2033", "2034", "2035" ], "wins": [ 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 ] }, { "name": "PHX", "year": ["2000", "2001"], "wins": [1, 4] } ]
内容的提问来源于stack exchange,提问作者Codeforlife1
相关产品推荐
相关产品推荐

