使用JavaScript DOM将第二个数组数据添加到表中第二列的问题

问题描述 投票:1回答:1

我的代码有问题。我目前在javascript中有两个数组,每个数组有4个元素。一个称为名称的名字,另一个称为数字分数的分数。它们取决于html文档中的用户输入。我有一个函数,该函数将在具有两列的表格中显示分数,第一列用于名称,第二列用于分数。名称的第一列工作正常,但分数的第二列显示正确的数字,但所有数字都在一行中。

Table that is supposed to have two columns

我尝试遍历分数数组并为每个分数在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);
	}
}
javascript html
1个回答
0
投票

最简单的方法是在添加名称的同一循环中添加分数,从而创建一个额外的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>
© www.soinside.com 2019 - 2024. All rights reserved.