gpt4 book ai didi

javascript - DOM:如何将表格转换为每行包含 2 个列表的表格?

转载 作者:行者123 更新时间:2023-11-28 02:32:52 26 4
gpt4 key购买 nike

如何将带有水平标题的 HTML 表格转换为每行包含两列表格的表格?

左侧的列将包含垂直标题,而右侧的列将包含相关值。

This fiddle显示了原始表格和将改为显示的表格的示例。

看看this couple of tables ,预期的行为将包括将带有水平标题的表格变成带有垂直标题的表格,但请注意,如果第一个表格有多行,第二个表格也应包含相同数量的行,但由表格的第一列是垂直标题,第二列是相应的值。

原始表格:

<table id="tableid">
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Smith</td>
<td>47</td>
</tr>
<tr>
<td>Bob</td>
<td>Jones</td>
<td>38</td>
</tr>
</tbody>

目标表:

<table id="tableid">
<tr>
<table>
<tr>
<th>Name</th>
<td>John</td>
</tr>
<tr>
<th>Surname</th>
<td>Smith</td></tr>
<tr>
<th>Age</th>
<td>47</td>
</tr>
</table>
</tr>
<tr>
<table>
<tr>
<th>Name</th>
<td>Bob</td>
</tr>
<tr>
<th>Surname</th>
<td>Jones</td></tr>
<tr>
<th>Age</th>
<td>38</td>
</tr>
</table>
</tr>
</table>

最佳答案

我希望这可能对您有所帮助,这实际上是将垂直表格反转为水平表格。

function inverse(){
var t= document.getElementsByTagName('tbody')[0];
r= t.getElementsByTagName('tr');
cols= r.length;
rows= r[0].getElementsByTagName('td').length;
let cell;
let next;
let tem;
i= 0;
tbod= document.createElement('tbody');

while(i<rows){
cell= 0;
tem= document.createElement('tr');
while(cell<cols){
next= r[cell++].getElementsByTagName('td')[0];
tem.appendChild(next);
}
tbod.appendChild(tem);
++i;
}
t.parentNode.replaceChild(tbod, t);
}

关于javascript - DOM:如何将表格转换为每行包含 2 个列表的表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49515270/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com