我的代码有问题。我目前在javascript中有两个数组,每个数组有4个元素。一个称为名称的名字,另一个称为数字分数的分数。它们取决于html文档中的用户输入。我有一个函数,该函数将在具有两列的表格中显示分数,第一列用于名称,第二列用于分数。名称的第一列工作正常,但分数的第二列显示正确的数字,但所有数字都在一行中。
我尝试遍历分数数组并为每个分数在index 1中创建一个a,我以为那是列所在的位置,但是我想我完全错了。该功能链接到按钮,并且必须保持该状态。一切正常,直到函数中第二个for循环为止。如果有人能帮我指出正确的方向,如何在第二列中添加得分数组值,那么看起来就像是一个有两列的表格就不错了。我正在学习javascript和html,感谢所有答复。
function displayScores() {
var table = document.getElementById("scores_table");
var h3 = document.createElement("h3");
document.getElementById("scores_table").appendChild(h3);
h3.innerHTML = "Scores";
h3.style.color = "blue";
var headerRow = table.insertRow(0);
var nameCell = headerRow.insertCell(0);
var scoreCell = headerRow.insertCell(1);
nameCell.innerHTML = "<b>Name</b>";
scoreCell.innerHTML = "<b>Score</b>";
for (var i = 0; i < names.length; i++) {
var txtNames = document.createTextNode(names[i]);
var tdNames = document.createElement("td");
var trNames = document.createElement("tr");
tdNames.appendChild(txtNames);
trNames.appendChild(tdNames);
table.appendChild(trNames);
}
//Everything works up till the second for loop, I cannot get the second array, scores, to show up in the second column
for (var j = 0; j < scores.length; j++) {
var cell = document.createElement("td");
var scoreColumn = trNames.insertCell(1);
cell.innerHTML = scores[j];
trNames.appendChild(cell);
cell.appendChild(scoreColumn);
scoreCell.appendChild(cell);
}
}
最简单的方法是在添加名称的同一循环中添加分数,从而创建一个额外的td
元素。我删除了第二个循环,并将创建分数单元移到了第一个循环。请参见下面的代码段:
var names = ['bob', 'john', 'sarah'];
var scores = [14, 23, 31];
function displayScores() {
var table = document.getElementById("scores_table");
var h3 = document.createElement("h3");
document.getElementById("scores_table").appendChild(h3);
h3.innerHTML = "Scores";
h3.style.color = "blue";
var headerRow = table.insertRow(0);
var nameCell = headerRow.insertCell(0);
var scoreCell = headerRow.insertCell(1);
nameCell.innerHTML = "<b>Name</b>";
scoreCell.innerHTML = "<b>Score</b>";
for (var i = 0; i < names.length; i++) {
var txtNames = document.createTextNode(names[i]);
var tdNames = document.createElement("td");
// add scores here
var txtScores = document.createTextNode(scores[i]);
var tdScores = document.createElement("td");
var trNames = document.createElement("tr");
tdNames.appendChild(txtNames);
tdScores.appendChild(txtScores);
trNames.appendChild(tdNames);
trNames.appendChild(tdScores);
table.appendChild(trNames);
}
}
displayScores();
<table id="scores_table"></table>