javascript - 如何将一列的 html5 表拆分为两列?
问题描述
我有一个包含一些嵌套数组的数组,这些嵌套数组由字符串和对象组成。我想根据他们在对象中的值显示超级英雄的名字,因此相应地为它们着色。
我成功地渲染了表格,其中数组中的每个项目都有一行 ( tr
),并且该行仅包含一列 ( td
)。但我无法呈现tr
每两个项目将有一行 ( ) 的表格。也就是说,td
每行将有两列 ( )。
这就是我现在所拥有的:
这就是我要的:
这是代码:
const tdEls = [];
const arr = [
[
'superman', {'flight': 'yes'}
],
[
'batman', {'flight': 'no'}
],
[
'green arrow', {'superstrength': 'no'}
],
[
'penguin', {'flight': 'yes'}
],
[
'shazam', {'flight': 'no'}
],
[
'wonderwoman', {'flight': 'yes'}
],
[
'cyborg', {'flight': 'no'}
],
[
'flash', {'superstrength': 'no'}
],
[
'martian', {'superstrength': 'no'}
],
[
'joker', {'flight': 'no'}
],
[
'robin', {'differentWorld': 'no'}
]
];
for ( let i = 0; i < arr.length; i++ ) {
if( arr[i][1].flight && arr[i][1].flight === 'yes' ) {
tdEls.push(`
<tr>
<td style="color:red;">${arr[i][0]}</td>
</tr>
`);
}
if( arr[i][1].flight && arr[i][1].flight === 'no' ) {
tdEls.push(`
<tr>
<td style="color:green;">${arr[i][0]}</td>
</tr>
`);
}
if( arr[i][1].superstrength && arr[i][1].superstrength === 'no') {
tdEls.push(`
<tr>
<td style="color:orange;">${arr[i][0]}</td>
</tr>
`);
}
if( arr[i][1].differentWorld && arr[i][1].differentWorld === 'no' ) {
tdEls.push(`
<tr>
<td style="color:blue;">${arr[i][0]}</td>
</tr>
`);
}
}
document.querySelector('table').innerHTML = tdEls.join('');
table{
border: 1px solid black;
}
table td{
border: 1px solid black;
}
<table></table>
解决方案
我们可以在两个单元格中分块并使用对象键和值作为类名
PS:企鹅不会飞。他用了一把飞行伞。
const arr = [ [ 'superman', {'flight': 'yes'} ], [ 'batman', {'flight': 'no'} ], [ 'green arrow', {'superstrength': 'no'} ], [ 'penguin', {'flight': 'yes'} ], [ 'shazam', {'flight': 'no'} ], [ 'wonderwoman', {'flight': 'yes'} ], [ 'cyborg', {'flight': 'no'} ], [ 'flash', {'superstrength': 'no'} ], [ 'martian', {'superstrength': 'no'} ], [ 'joker', {'flight': 'no'} ], [ 'robin', {'differentWorld': 'no'} ] ];
const chunk = (arr, len) => {
let chunks = [], i = 0, n = arr.length;
while (i < n) chunks.push(arr.slice(i, i += len));
return chunks;
};
const tdEls = arr.map(hero => `<td class="${Object.keys(hero[1])}${Object.values(hero[1])}">${hero[0]}</td>`)
document.querySelector('table tbody').innerHTML = chunk(tdEls,2).map(cnk => `<tr>${cnk.join("")}</tr>`).join("")
table {
border: 1px solid black;
}
table td {
border: 1px solid black;
}
.flightyes {
color: red
}
.flightno {
color: green
}
.superstrengthno {
color: orange
}
.differentWorldno {
color: blue
}
<table><tbody></tbody></table>
推荐阅读
- javascript - Javascript推送到数组高级
- java - Java中的增量会改变它的直接价值吗?
- c++ - 长度转换程序无法在 C++ 中转换十进制数
- php - XAMPP WordPress PHP VSCode Xdebug 没有本地人
- docker - 从 Dockerfile 访问 `docker run` 参数
- javascript - 在greasemonkey脚本中打印“事件”对象会静默终止执行,如何查看“事件”?
- android - 意图和配置正确清单
- sql - 如果不为空,则更新列
- laravel - Laravel FileSystem 创建 CloudFront 签名 URL
- gdb - 尝试使用 ROP 进行利用时 gdb 和直接执行的不同行为