如何使用原生JS从对象数组创建HTML表格并应用CSS样式
原生JavaScript实现方案
按目标DOM结构逐层创建元素,遍历数据填充内容即可,完整可运行代码如下:
// 源数据数组 let arr = [ {name: 'Player1',score:10}, {name: 'Player2',score: 7}, {name: 'Player3',score:3} ]; // 创建外层容器与表格主体 const container = document.createElement('div'); container.className = 's-table-container'; const table = document.createElement('table'); table.className = 's-table'; // 构建表头 const thead = document.createElement('thead'); const headRow = document.createElement('tr'); ['Name', 'Score'].forEach(colText => { const th = document.createElement('th'); th.textContent = colText; headRow.appendChild(th); }); thead.appendChild(headRow); table.appendChild(thead); // 遍历数据构建表体 const tbody = document.createElement('tbody'); arr.forEach(item => { const row = document.createElement('tr'); [item.name, item.score].forEach(cellVal => { const td = document.createElement('td'); td.textContent = cellVal; row.appendChild(td); }); tbody.appendChild(row); }); table.appendChild(tbody); container.appendChild(table); // 将生成完成的表格插入页面指定位置,示例为插入到body末尾 document.body.appendChild(container);
如果你的数据字段不固定,不需要硬编码表头列,将固定表头的数组替换为以下代码即可自动适配字段:
// 自动读取第一条数据的字段名,首字母大写后作为表头 const headers = Object.keys(arr[0]).map(key => key.charAt(0).toUpperCase() + key.slice(1));
CSS样式应用方法
生成表格时已经给容器和表格加上了对应的类名,直接按类名匹配写样式即可,常用实现方式有两种:
- 写独立CSS规则:在页面的
<style>标签或独立CSS文件中定义样式,浏览器会自动给匹配类名的元素生效,参考样式如下:
.s-table-container { overflow-x: auto; margin: 16px 0; } .s-table { width: 100%; border-collapse: collapse; text-align: left; } .s-table th { background-color: #f5f7fa; padding: 12px 16px; font-weight: 600; border-bottom: 2px solid #e4e7ed; } .s-table td { padding: 12px 16px; border-bottom: 1px solid #e4e7ed; } .s-table tbody tr:hover { background-color: #fafafa; }
- 行内样式:如果样式逻辑非常简单,也可以在JS创建元素时直接通过
element.style.xxx = xxx的方式给元素加样式,这种方式维护成本高,不推荐复杂场景使用。
内容的提问来源于stack exchange,提问作者RaptorRV
相关产品推荐
相关产品推荐

