我正在尝试更新数组中的表行。分配要求是该表必须预先存在且没有数据,因此不允许添加行数据-我需要替换单元格中的数据。
HTML表格
<table id="test">
<thead>
<tr>
<th></th>
<th>Jan</th>
<th>Feb</th>
<th>Mar</th>
</tr>
</thead>
<tbody>
<tr>
<th>Wind Speed</th>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th>Solar Radiation</th>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
jQuery代码
var arr = [[13,14,15],[3,4,5]];
$.each(arr, function(rowIndex, r){
$.each(r, function(colIndex, c){
$("td").text(c);
});
});
它应该从单元格中的数组输出数据,但是在空单元格中仅输出5,这是最后一个数组中的最后一个值。 我确定我缺少一些简单的东西,但是我无法弄清楚。任何帮助将不胜感激!
答案 0 :(得分:2)
您可以这样做:
$("#test tbody tr:eq(" + rowIndex + ") td:eq(" + colIndex + ")").text(c);
问题是,当您使用$("td").text(c);
时,请为每个td
设置相同的值。
工作演示
var arr = [
[13, 14, 15],
[3, 4, 5]
];
$.each(arr, function(rowIndex, r) {
$.each(r, function(colIndex, c) {
$("#test tbody tr:eq(" + rowIndex + ") td:eq(" + colIndex + ")").text(c);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="test">
<thead>
<tr>
<th></th>
<th>Jan</th>
<th>Feb</th>
<th>Mar</th>
</tr>
</thead>
<tbody>
<tr>
<th>Wind Speed</th>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th>Solar Radiation</th>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>