我正在尝试从 2 个不同的 JavaScript 数据数组构建 2 个 html 表。
第一个表构建得很好,结构看起来很棒,但第二个表没有填充数据。
我尝试调整命名,但我认为因为它两次都在寻找“tbody”。
是否有另一个变量来调整这个,或者也许有更好的方法从 2 个不同的数据数组中获得 2 个单独的表?
我交换了命名并向 tbody 添加了 ID 标签,结果没有变化。我本来打算重命名数据表,但似乎抓取 tbody 的第二个表的构造只是调整第一个 tbody。
<div style="float: left;margin-right:10px">
<table>
<thead>
<tr align="center">
<th><h3>Name</h3></th>
<th><h3>Time</h3></th>
<th><h3>Temp</h3></th>
<th><h3>Peel</h3></th>
</tr>
</thead>
<tbody id="tbody"></tbody>
</table>
</div>
<script>
const data = [
{name: "Apple", time: "25sec", temp: "100F", peel: "Peeler"},
{name: "Orange", time: "50sec", temp: "200F", peel: "Knife"},
]
const table = document.querySelector('tbody')
data.forEach((item) => {
table.insertAdjacentHTML( 'beforeend', `<tr>
<td>${item.name}</td>
<td>${item.time}</td>
<td>${item.temp} </td>
<td>${item.peel}</td>
</tr>`)
})
</script>
<div style="float: left">
<table>
<thead>
<tr align="center">
<th><h3>Name</h3></th>
<th><h3>Time</h3></th>
<th><h3>Temp</h3></th>
<th><h3>Peel</h3></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script>
<script>
const data = [
{name: "Apple", time: "25sec", temp: "100F", peel: "Peeler"},
{name: "Orange", time: "50sec", temp: "200F", peel: "Knife"},
]
const table = document.querySelector('tbody')
data.forEach((item) => {
table.insertAdjacentHTML( 'beforeend', `<tr>
<td>${item.name}</td>
<td>${item.time}</td>
<td>${item.temp}</td>
<td>${item.peel}</td>
</tr>`)
})
</script> Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您的代码存在一些问题。 您在第一个
<script>标记中将data和table声明为常量,然后尝试在第二个<script>标记中重新评估它们的值。 (常量变量不能重新赋值)。 此外,document.querySelector('tbody')将始终选择在页面上找到的第一个<tbody>元素。这将导致选择同一个表两次。这就是我重构这段代码的方式,但是有无数种方法可以解决这个问题。
考虑将行创建提取到函数中,并为两个 tbody 元素提供唯一的 ID 来区分它们。
function addRows(tbody, data) { data.forEach((item) => { tbody.insertAdjacentHTML('beforeend', `
${item.name}
${item.time}
${item.temp}
${item.peel}
`)
});
}
const data1=[{name:"Apple",time:"25sec",temp:"100F",peel:"Peeler"},{name:"Orange",time:"50sec",temp:"200F",peel:"Knife"},];
const tbody1 = document.querySelector('#tbody1');
addRows(tbody1, data1);
const data2=[{name:"Apple",time:"25sec",temp:"100F",peel:"Peeler"},{name:"Orange",time:"50sec",temp:"200F",peel:"Knife"},];
const tbody2 = document.querySelector('#tbody2');
addRows(tbody2, data2);