首页 > 解决方案 > 如何将一列的 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>

标签: javascripthtmljqueryarrays

解决方案


我们可以在两个单元格中分块并使用对象键和值作为类名

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>


推荐阅读