使用Javascript比较两个表之间的差异



const firstTable = document.getElementById('table_1')
const secondTable = document.getElementById('table_2')
const rows1 = firstTable.rows
const rows2 = secondTable.rows
for (let i = 0; i < rows1.length; i++) {
for (let x in rows1[i].cells) {
let col = rows1[i].cells[x]
console.log(col)
}
for (let j = 0; j < rows2.length; j++) {

}
}
table {
border: 1px solid black;
}
td {
border: 1px solid black;
}
<table id="table_1">
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
</tr>
<tr>
<td>1</td>
<td>per</td>
<td style="background-color:red">27</td>
</tr>
<tr>
<td>2</td>
<td>Tom</td>
<td>25</td>
</tr>
<tr>
<td>notexist</td>
<td></td>
<td></td>
</tr>
</table>
<table id="table_2">
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
</tr>
<tr>
<td>1</td>
<td>per</td>
<td style="background-color:green">25</td>
</tr>
<tr>
<td>2</td>
<td>Tom</td>
<td>25</td>
</tr>
<tr>
<td>3</td>
<td>alex</td>
<td>33</td>
</tr>
</table>

我需要在javascript中动态比较这两个表,以获得与代码中的表类似的结果。如果id相等,我需要比较每行中的每个单元格。如果id在第二个表中不存在,我需要写这个不存在。例如,我把年龄放在第一个表的第一行,而不是第二个表的第二行。如果不相等,则将背景颜色设置为红色或绿色。

从DOMtable中,如果它们是相同的(结构(,您可以在其中一个的TDs上进行循环,并将textContent与位于相同位置的另一个进行比较:

这是一个的例子

const firstTable = document.querySelectorAll("#table1 td");
const secondTable = document.querySelectorAll("#table2 td");
// loop on one of the table if both are of identical structure, else it is pointless
for (let i = 0; i < firstTable.length; i++) {
if (firstTable[i].textContent !== secondTable[i].textContent) {
firstTable[i].classList.add('redbg');// here do what you need to when not equal
}
// else { /* do what you need to if equal*/ }
}
.redbg {
background: red;
}
<table id="table1">
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
</tr>
<tr>
<td>1</td>
<td>per</td>
<td>27</td>
</tr>
<tr>
<td>2</td>
<td>Tom</td>
<td>25</td>
</tr>
<tr>
<td>notexist</td>
<td></td>
<td></td>
</tr>
</table>
<table id="table2">
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
</tr>
<tr>
<td>1</td>
<td>per</td>
<td>25</td>
</tr>
<tr>
<td>2</td>
<td>Tom</td>
<td>25</td>
</tr>
<tr>
<td>3</td>
<td>alex</td>
<td>33</td>
</tr>
</table>

从数组中,idea可以是第一个循环上的同一个循环,检查第一个和第二个是否在同一位置获得了相同的内容,并在构建表时添加类。

最新更新