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++) {
}
}
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 我需要写这个不存在。例如,我将年龄放在第一个表的第一行而不是第二个表的第二行中的年龄。如果不相等,则将背景颜色设置为红色或绿色。
从 DOM 中table
,如果它们相同(结构),您可以在其中一个的TD
s上进行循环,并与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 可以是第一个的相同循环,并检查 firstone 和 second 在同一位置是否获得相同的内容,并在构建表时添加类。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句