1 回答

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超5個(gè)贊
你確實(shí)很接近!
一種簡(jiǎn)化相當(dāng)多的方法是保留對(duì)當(dāng)前“標(biāo)題”單元格的引用,即您想要增加的單元格rowspan
。這樣你根本不需要處理索引,產(chǎn)生一個(gè)非常簡(jiǎn)單的算法:
對(duì)于每一行
將headerCell的rowSpan增加 1
刪除firstCell
將headerCell設(shè)置為firstCell
將firstCell設(shè)置為行的第一個(gè)單元格
如果這是第一行或firstCell的文本與headerCell的文本不同
除此以外
在 JavaScript 中,它看起來(lái)像這樣:
const table = document.querySelector('table');
let headerCell = null;
for (let row of table.rows) {
const firstCell = row.cells[0];
if (headerCell === null || firstCell.innerText !== headerCell.innerText) {
headerCell = firstCell;
} else {
headerCell.rowSpan++;
firstCell.remove();
}
}
table, tr, td {
border: solid 1px black;
}
<table>
<tr>
<td>fish</td>
<td>salmon</td>
</tr>
<tr>
<td>fish</td>
<td>cod</td>
</tr>
<tr>
<td>fish</td>
<td>plaice</td>
</tr>
<tr>
<td>bird</td>
<td>robin</td>
</tr>
<tr>
<td>bird</td>
<td>crow</td>
</tr>
</table>
添加回答
舉報(bào)