gpt4 book ai didi

javascript - 无法将数组数据加载到 Html

转载 作者:行者123 更新时间:2023-11-30 11:00:54 25 4
gpt4 key购买 nike

我正在尝试使用 google apps 脚本将数组数据填充到 html 中。

我已经花了很多时间来解决问题,但找不到缺少的东西:-

HTML 标签 :-

   <table class="highlight">
<thead>
<tr>
<th>Delta</th>
<th>Assigned</th>
<th>Reviewed</th>
<th>Pending</th>

</tr>
</thead>

<tbody id="perf">

</tbody>
</table>

<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<?!= include('table1-js'); ?>

Javascript:-

<script>

var data = [

[1,2,3,4]
[5,6,7,8]
[9,10,11,12]
[9,10,11,12]

];
document.addEventListener('DOMContentLoaded', function(){

getTable1Data(data);
});

function getTable1Data(dataArray){


var tbody = document.getElementById('perf');

dataArray.forEach(function(r){

var row = document.createElement("tr");
var col1 = document.createElement("td");
col1.textContent = r[0];
var col2 = document.createElement("td");
col2.textContent = r[1];
var col3 = document.createElement("td");
col3.textContent = r[2];
var col4 = document.createElement("td");
col4.textContent = r[3];

row.appendChild(col1);
row.appendChild(col2);
row.appendChild(col3);
row.appendChild(col4);

tbody.appendChild(row);

});

}

</script>

目前结果只是在 HTML 中显示的标题,没有数据被附加到表中。

最佳答案

您的 data 数组中出现语法错误。用逗号分隔每个元素:

var data = [
[1, 2, 3, 4], // Element separation comma
[5, 6, 7, 8],
[9, 10, 11, 12],
[9, 10, 11, 12]
];

此外,如果这是您正在处理的数据的结构,您可以通过执行两个继承 forEach 来大大简化您的代码:

const data = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[9, 10, 11, 12]
];
document.addEventListener('DOMContentLoaded', function() {
getTable1Data(data);
});

function getTable1Data(dataArray) {
let tbody = document.getElementById('perf');
dataArray.forEach(function(r) {
let row = document.createElement("tr")
r.forEach(function(c) {
let col = document.createElement("td")
col.innerText = c
row.appendChild(col)
})
tbody.appendChild(row);
});

}
<table class="highlight">
<thead>
<tr>
<th>Delta</th>
<th>Assigned</th>
<th>Reviewed</th>
<th>Pending</th>
</tr>
</thead>
<tbody id="perf"></tbody>
</table>

关于javascript - 无法将数组数据加载到 Html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57775319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com