使用JSON数组在JavaScript中动态创建并填充表格失败求助
解决JavaScript创建并填充JSON数据表格的问题
嘿,我看你已经开了个好头,但代码没完成,所以表格没法正常显示出来。别担心,我帮你补全并优化了代码,下面是完整的可运行版本,我会给你拆解关键步骤:
完整可运行代码
<script> var jArray = [ {"name": "julio", "lastname":"Rodriguez","edad":33 }, {"name": "maría", "lastname":"Díaz","edad":36 }, {"name": "rosa", "lastname":"Rodriguez","edad":59 }, {"name": "julio", "lastname":"Pereira","edad":68 } ]; // 创建表格并设置基础样式 var t = document.createElement('table'); t.style.border = '2px solid blue'; t.style.borderCollapse = 'collapse'; // 合并边框,避免双边框 // 构建表头部分 var thead = document.createElement('thead'); var headerRow = document.createElement('tr'); // 定义表头文本 var headers = ['Name', 'Last Name', 'Edad']; headers.forEach(headerText => { var th = document.createElement('th'); th.textContent = headerText; th.style.border = '1px solid blue'; th.style.padding = '8px'; headerRow.appendChild(th); }); thead.appendChild(headerRow); t.appendChild(thead); // 构建表体(你之前只创建了tbody,没填充内容) var tb = document.createElement('tbody'); // 遍历JSON数组,生成每一行数据 jArray.forEach(person => { var row = document.createElement('tr'); // 为每个属性创建单元格并填充数据 Object.values(person).forEach(value => { var cell = document.createElement('td'); cell.textContent = value; cell.style.border = '1px solid blue'; cell.style.padding = '8px'; row.appendChild(cell); }); tb.appendChild(row); }); // 将表体添加到表格 t.appendChild(tb); // 最后把表格添加到页面中,否则不会显示 document.body.appendChild(t); </script>
关键修复点说明
- 补全表头:表格需要表头来明确列含义,这里我们通过遍历表头数组生成
<th>元素,让结构更清晰 - 遍历填充数据:用
forEach循环遍历你的JSON数组,为每个对象生成一行;再通过Object.values()快速获取对象的属性值,生成对应的单元格 - 样式优化:添加了
borderCollapse合并边框,还给单元格加了内边距,让表格看起来更规整 - DOM插入:最后必须把创建好的表格添加到页面的DOM节点(比如
document.body)里,否则表格只会存在于内存中,不会显示在页面上
内容的提问来源于stack exchange,提问作者Julio Rodriguez
相关产品推荐
相关产品推荐

