如何用JS从对象数组生成指定布局的动态HTML表格?
实现方案
1. 准备页面容器
先在HTML中添加一个用来承载所有表格的容器:
<div id="form-output"></div>
2. JS动态生成表格
使用ES6模板字符串拼接HTML结构,逻辑清晰易读:
const formPages = [ { "name": "page1", "response": [ { "question": "Question 1", "response": "Hello!" }, { "question": "Question 2", "response": "Hello again!" } ] }, { "name": "page2", "response": [ { "question": "Question 3", "response": "Bye!" }, { "question": "Question 4", "response": "Bye again!" } ] } ]; // 获取页面承载容器 const outputContainer = document.getElementById('form-output'); // 遍历每个页面生成对应HTML const html = formPages.map(page => { // 转换page名称为标题格式(page1 → Page 1) const pageTitle = page.name.replace(/page(\d+)/, (_, num) => `Page ${num}`); // 生成表格的所有数据行 const tableRows = page.response.map(item => ` <tr> <td>${item.question}</td> <td>${item.response}</td> </tr> `).join(''); // 返回当前页面的完整HTML结构 return ` <p><strong>${pageTitle}</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Question</th> <th>Response</th> </tr> </thead> <tbody> ${tableRows} </tbody> </table> </div> `; }).join(''); // 将生成的HTML插入到页面中 outputContainer.innerHTML = html;
关键逻辑说明
- 遍历页面数组:用
Array.map()遍历每个页面数据,生成单个页面的HTML片段 - 标题格式转换:通过正则表达式把
page1这类名称转换成Page 1的标题样式 - 生成表格行:遍历每个问题-回答对,拼接成表格的
<tr>元素,再用join('')将数组转为字符串 - 插入页面:把所有页面的HTML片段拼接后,通过
innerHTML插入到指定容器
安全提示
如果数据包含用户输入内容(存在XSS风险),需要对文本进行转义处理,可使用以下工具函数:
function escapeHtml(text) { const div = document.createElement('div'); div.textContent = text; return div.innerHTML; }
使用时将${item.question}替换为${escapeHtml(item.question)},${item.response}同理即可。
内容的提问来源于stack exchange,提问作者joshsutheran
相关产品推荐
相关产品推荐

