如何用JavaScript将数组数据插入动态创建的表格?
解决方案:点击按钮生成包含水果数组的表格
实现步骤
1. HTML结构
先准备触发按钮和表格承载容器:
<button id="showFruitsBtn">显示水果表格</button> <div id="tableContainer"></div>
2. JavaScript实现
按照需求完成showFruits函数,并绑定按钮点击事件:
var fruits = ['apple', 'orange', ' grape', 'banana', 'guava', ' watermelon', 'mango']; function showFruits() { // 获取表格容器 const container = document.getElementById('tableContainer'); // 清空容器,避免重复生成表格 container.innerHTML = ''; // 创建表格并添加边框 const table = document.createElement('table'); table.style.borderCollapse = 'collapse'; table.border = '1'; // 创建表格行 const row = document.createElement('tr'); // 遍历数组生成单元格 fruits.forEach(fruit => { const cell = document.createElement('td'); // 去除水果名称前后的多余空格 cell.textContent = fruit.trim(); cell.style.padding = '8px 12px'; row.appendChild(cell); }); // 组装表格并插入容器 table.appendChild(row); container.appendChild(table); } // 绑定按钮点击事件 document.getElementById('showFruitsBtn').addEventListener('click', showFruits);
关键细节说明
- 每次生成表格前清空容器,防止多次点击出现重复内容
- 用
trim()处理数组元素的前后空格,保证显示的水果名称格式整洁 - 通过DOM API动态创建元素,比拼接HTML字符串更安全、易维护
内容的提问来源于stack exchange,提问作者Brijesh Gurung
相关产品推荐
相关产品推荐

