我在HTML中有这个(名称,值)表,我希望填充'值'一些计算后的列。
'名称'列在加载网页时填写,而“#”值则为#39;当时列仍为空白。
执行一些计算后,我想填充“'值”'对应于' name'的每一行的列,按顺序排列。从1 - > Ñ
我的页面的作用:
下一步:
我想填充'值'存储在'值'中的每个元素的列阵列,连续地,即从1 - >; Ñ
这里有一些代码:
JavaScript - 根据开头收到的数字动态创建表格
var playerTable = document.getElementById("player_table");
var player_table_row, player_table_datacell1, player_table_datacell2;
var value;
//no_of_players contains the number of rows
for ( var i = 0; i < no_of_players; i++)
{
//inserts i'th row
player_table_row = playerTable.insertRow(i);
//Insert first datacell for the row
player_table_datacell1 = player_table_row.insertCell( 0 );
//Insert second datacell for the row
player_table_datacell2 = player_table_row.insertCell( 1 );
//Inserts the name for the i'th row in the 'name' column
//players_list is the array containing all the names
player_table_datacell1.innerHTML = players_list[i];
//Leave the second cell i.e. 'value' column blank
player_table_datacell2.innerHTML = "";
value[i] = /* Some computations */
}
该表的HTML代码,它只是一个简单的
<table id = "player_table">
<th>Name</th>
<th>Value</th>
</table>
预期产出:
Name Value
A 5
B 2
C 19
我已提前计算了这些值5,2,19,现在只需要在HTML表格中填充它们。我目前的表格如下:
Name Value
A
B
C
答案 0 :(得分:0)
我假设您的计算需要某种用户输入。这就是为什么你不能进行计算然后用名称和计算值向表中添加行的原因。
这是一种做法。我只是为每个值单元格设置id并使用id进行更新。希望它有所帮助:)
<body>
<table id = "player_table">
<thead>
<th>Name</th>
<th>Value</th>
</thead>
</table>
<script type="text/javascript">
process();
function process() {
var playerTable = document.getElementById("player_table");
var player_table_row, player_table_datacell1, player_table_datacell2;
var value;
//hard coding for testing purposes
no_of_players = 3;
var players_list = ["A", "B", "C"];
//no_of_players contains the number of rows
for (var i = 0; i < no_of_players; i++) {
//inserts i'th row
player_table_row = playerTable.insertRow(i + 1);
//Insert first datacell for the row
player_table_datacell1 = player_table_row.insertCell(0);
//Insert second datacell for the row
player_table_datacell2 = player_table_row.insertCell(1);
player_table_datacell2.id = "value_cell_" + String(i);
//Inserts the name for the i'th row in the 'name' column
//players_list is the array containing all the names
player_table_datacell1.innerHTML = players_list[i];
//Leave the second cell i.e. 'value' column blank
player_table_datacell2.innerHTML = "";
//value[i] = /* Some computations */
}
value = ["100", "200", "300"]; //hard coding for testing purposes
updateValueColumn(value);
}
function updateValueColumn(value) {
var value_cell;
for (var i = 0; i < value.length; i++) {
value_cell = document.getElementById("value_cell_" + String(i));
value_cell.innerHTML = value[i];
}
}
</script>
</body>
答案 1 :(得分:0)
使用如下生成的表:
<table id = "player_table">
<tr>
<th>Name</th>
<th>Value</th>
</tr>
<tr>
<td>A</td>
<td></td>
</tr>
<tr>
<td>B</td>
<td></td>
</tr>
<tr>
<td>C</td>
<td></td>
</tr>
</table>
您可以使用此代码将第二列作为数组:
var valueCells = document.querySelectorAll("#player_table tr td:nth-child(2)");
然后在某个循环中为每个单元格设置innerHTML。
valueCells[i].innerHTML = value[i];