我正在尝试基于数组和for循环生成表。我已经尽力自己解决这个问题没有结果。在for循环中你可以看到我已经尝试但没有结果。我希望表只从数组和for循环生成,它看起来像这样:
|Tresort | 1915 | 1950 | 1970 | 1990 | 1992 | 2000 |
|Furu | 20 | 31 | 53 | 89 | 102 | 117 |
|Gran | 23 | 39 | 72 | 89 | 92 | 99 |
|Lauvtre | 4 | 6 | 8 | 12 | 15 | 18 |
这是我的代码:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table id="tabell" border="1px">
</table>
<script>
function tabellOp() {
var measurement = [ [20,31,53,89,102,117], [23,39,72,89,92,99], [4,6,8,12,15,18] ];
var tree = ["furu", "gran", "lauvtre"];
var year = [1915,1950,1970,1990,1992,2000]
var tabellget = document.querySelector("#tabell");
var row="";
for(var i =0;i<tree.length;i++) {
row = "<tr><th> Tresort</th></tr>";
row += "<tr><th>" + tree[i] + "</tr></th>";
}
tabellget.innerHTML = row;
}
window.onload=tabellOp;
</script>
</body>
</html>
答案 0 :(得分:0)
首先,你的for循环没有使用测量数组或年份数组 - 你只是添加树数组中的元素。第二点 - 你正在和#34; Tresort&#34;在每个循环迭代中。
最后,您的结果将具有
的值"<tr><th>Tresort</th></tr>
<tr><th>furu</th></tr>
<tr><th>Tresort</th></tr>
<tr><th>gran</th></tr>
<tr><th>Tresort</th></tr>
<tr><th>lauvtre</th></tr>"
这不是你想要的。此外,在循环的第二行中,您在关闭th标记之前关闭tr标记,这也可能导致错误。
答案 1 :(得分:0)
基于代码的简单解决方案(see on jsfiddle)
function tabellOp() {
var measurement = [ [20,31,53,89,102,117], [23,39,72,89,92,99], [4,6,8,12,15,18] ];
var tree = ["furu", "gran", "lauvtre"];
var year = [1915,1950,1970,1990,1992,2000];
var tabellget = document.querySelector("#tabell");
var row = "<tr><th> Tresort</th>";
for (var i = 0; i < year.length; i++) {
row += "<th>" + year[i] + "</th>";
}
row += "</tr>";
for (var i = 0; i < tree.length; i++) {
row += "<tr><th>" + tree[i] + "</th>";
for (var j = 0; j < measurement[i].length; j++) {
row += "<td>" + measurement[i][j] + "</td>";
}
row += "</tr>";
}
tabellget.innerHTML = row;
}
window.onload = tabellOp;