javascript - JavaScript 中的多列
问题描述
我是 JavaScript 新手。我写了 forEach ,每次我在数据库中添加一些东西时,头表都会重复。我需要 col 留下来,当我向数据库添加新内容时,它会添加到行中。
这是一个屏幕截图来说明我的意思:
代码:
import {http} from "./http.js";
document.addEventListener("DOMContentLoaded", getProducts);
function getProducts() {
http
.get('http://localhost:3000/products')
.then((data) =>{
let output = "";
data.forEach((product) => {
output += `
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col">Clasa</th>
<th scope="col">Numar Elevi</th>
<th scope="col">Profesor</th>
<th scope="col">Media Notelor</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">${product.id}</th>
<td>${product.numar}</td>
<td>${product.profesor}</td>
<td>${product.elevi}</td>
<td>${product.media}</td>
</tr>
</tbody>
</table>
`;
})
document.getElementById('table').innerHTML = output;
});
}
解决方案
// As the Ajax call is not the issue here, simulate some sample data
const data = [
{ id:1, numar: "a IV-a A", profesor: 23, elevi: "Matel Marian", media: "8.32"},
{ id:2, numar: "a VI-a C", profesor: 26, elevi: "Cornel Ababei", media: "7.96"},
{ id:3, numar: "ss", profesor: "sss", elevi: "sss", media: "sss"},
];
// The <table>, <thead>, and <tbody> tags are needed just once
let output = `<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col">Clasa</th>
<th scope="col">Numar Elevi</th>
<th scope="col">Profesor</th>
<th scope="col">Media Notelor</th>
</tr>
</thead>
<tbody id="tbody">`;
// Then for each item, append a <tr>...</tr> element
data.forEach((product) => {
output += `
<tr>
<th scope="row">${product.id}</th>
<td>${product.numar}</td>
<td>${product.profesor}</td>
<td>${product.elevi}</td>
<td>${product.media}</td>
</tr>`;
});
// Finally, close off with </table>
output += "</tbody></table>";
document.getElementById("table").innerHTML = output;
// Say later you have another Ajax call and got another item.
const add = () => {
// simulated data:
const newItem = I = { id:4, numar: "b IX-c D", profesor: 88, elevi: "Richard Feyman", media: "9.99"};
let row = document.createElement("tr");
row.innerHTML = `<td>${I.id}</td><td>${I.numar}</td><td>${I.profesor}</td><td>${I.elevi}</td><td>${I.media}</td>`;
const tbody = document.getElementById("tbody");
tbody.appendChild(row);
}
.table, .table td, .table th {
border: solid 1px black
}
<div id="table"></div>
<p>
<button onclick="add()">Add another row</button>
</p>
推荐阅读
- python - 如何生成点分隔字符串的子字符串?
- javascript - 使用 vanilla Javascript 构建购物车功能
- intellij-idea - 如何在 Intellij 中重置“如果由 Y 注释,则抑制 X 警告”?
- docker - 如何在 Pycharm Docker Interpreter 中设置 docker 容器名称
- c++ - 混合虚拟和模板
- r - 同时创建多个子集
- azure - Azure Key Vault 扩展在更新后未自动绑定
- .net - 如何加入 TransactionScope?
- r - 仅当 dummy = 0 时删除某些列中带有 na 的行
- c - 无数组的最小数的序数