如何用JAVAScript写一个多行多列的表格,用while语句
时间: 2024-09-18 18:13:31 浏览: 52
在JavaScript中,你可以使用HTML结构来创建多行多列的表格,并结合while循环来动态生成内容。以下是一个简单的示例,展示如何使用while循环来填充表格:
```javascript
// 定义数据
let data = [
{ name: 'Row 1, Col 1', value: 'Value 1' },
{ name: 'Row 1, Col 2', value: 'Value 2' },
// ... 可以添加更多的行和列
];
// 获取表格元素
const table = document.createElement('table');
const tbody = document.createElement('tbody');
// 设置表格样式(例如,这只是基本样式,你可以根据需要调整)
table.style.width = '100%';
table.border-collapse = 'collapse';
// 使用while循环生成每一行
let i = 0;
while (i < data.length) {
const row = document.createElement('tr');
// 生成每一列
let j = 0;
while (j < 2) { // 这里假设每行有两个列,你可以根据实际需求修改
const cell = document.createElement('td');
cell.textContent = `${data[i].name}, ${data[i].value}`;
row.appendChild(cell);
j++;
}
// 将行添加到表体
tbody.appendChild(row);
i++;
}
// 将表体添加回表格
table.appendChild(tbody);
// 最后将完整的表格添加到页面上(这里假设你想要插入到document.body中)
document.body.appendChild(table);
阅读全文
相关推荐
















