我正在处理以下代码。我试图弄清楚为什么我不能在一行中附加所有<td>
?我想做的是在乞求每一行的末尾附加一个自定义<td>
,如下所示:
<tr>
<td>Defult TD</td>
<td>52</td>
<td>16</td>
<td>140</td>
<tr>
<tr>
<td>Defult TD</td>
<td>54</td>
<td>16</td>
<td>145</td>
<tr>
但是我得到的是
<tr>
<td>Defult TD</td>
</tr>
<tr>
<td>52</td>
<td>16</td>
<td>140</td>
<tr>
<tr>
<td>Defult TD</td>
</tr>
<tr>
<td>54</td>
<td>16</td>
<td>145</td>
<tr>
var sizes= [
[52, 16, 140],
[54, 16, 145]
];
var table = $('#size-rows');
var row, cell;
for (var i = 0; i < sizes.length; i++) {
row = $('<tr />');
table.append(row);
cell = $('<td>Default TD</td>')
for (var j = 0; j < sizes[i].length; j++) {
cell.append('<td>' + sizes[i][j] + '</td>');
row.append(cell);
}
}
td{
border:1px solid #ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody id="size-rows"> </tbody>
</table>
答案 0 :(得分:1)
您要附加到<td>
,而是将cell
和下一个<td>
附加到row
:
var sizes = [
[52, 16, 140],
[54, 16, 145]
];
var table = $('#size-rows');
var row, cell;
for (var i = 0; i < sizes.length; i++) {
row = $('<tr />');
table.append(row);
cell = $('<td>Default TD</td>');
row.append(cell);
for (var j = 0; j < sizes[i].length; j++) {
row.append('<td>' + sizes[i][j] + '</td>');
}
}
td {
border: 1px solid #ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody id="size-rows"> </tbody>
</table>
答案 1 :(得分:0)
这是使用map函数的解决方案。
var sizes= [
[52, 16, 140],
[54, 16, 145]
];
$('#size-rows').append(
sizes.map(
x => `<tr>
<td>Default TD</td>${x.map(y => `<td>${y}</td>`)}
</tr>`
)
);
td{
border:1px solid #ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody id="size-rows"> </tbody>
</table>