如何用JS创建首行3列其余行4列的表格并填充动态集合数据
JavaScript 动态生成指定格式表格
实现思路
- 将
apptid_set11集合转换为数组,便于按顺序遍历取值 - 创建表格DOM结构,首行作为表头,包含3个单元格
- 遍历数据数组,每4个元素生成一行,最多生成20行,从第二行开始填充表格内容
完整代码
// 获取目标集合(你提供的代码片段) const apptid_divs11 = [...document.querySelectorAll('.apptSearchResultSelected')]; const apptid_set11 = new Set(apptid_divs11.map(div => div.textContent.trim().split('#')[0])); // 将Set转换为数组,方便遍历 const apptidArray = Array.from(apptid_set11); // 创建表格元素 const table = document.createElement('table'); table.border = '1'; // 可选:添加边框方便查看 // 创建表头行 const headerRow = document.createElement('tr'); // 表头3个单元格,可自定义文本 for (let i = 0; i < 3; i++) { const th = document.createElement('th'); th.textContent = `表头${i + 1}`; headerRow.appendChild(th); } table.appendChild(headerRow); // 计算需要生成的行数:最多20行,或根据数据量决定 const maxRows = Math.min(20, Math.ceil(apptidArray.length / 4)); // 生成内容行 for (let rowIndex = 0; rowIndex < maxRows; rowIndex++) { const row = document.createElement('tr'); // 每行4个单元格,计算当前行的起始索引 const startIndex = rowIndex * 4; for (let cellIndex = 0; cellIndex < 4; cellIndex++) { const cell = document.createElement('td'); // 取对应位置的数据,若无数据则留空 const data = apptidArray[startIndex + cellIndex]; cell.textContent = data || ''; row.appendChild(cell); } table.appendChild(row); } // 将表格添加到页面指定容器(示例:添加到body,可替换为你的目标容器) document.body.appendChild(table);
关键说明
- Set转数组:
Array.from(apptid_set11)将集合转换为数组,解决Set无法通过索引直接访问元素的问题 - 行数控制:
Math.min(20, Math.ceil(apptidArray.length / 4))确保生成的行数不超过20行 - 单元格填充:每行遍历4次,从数组中取对应位置的数据,若数据不足则单元格留空
- DOM创建:使用原生DOM方法动态生成表格,避免字符串拼接的潜在问题
内容的提问来源于stack exchange,提问作者Dani Misi
相关产品推荐
相关产品推荐

