<table border=1px cellspacing="0" width="800px" height="300px" cellpadding="0px">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
let tr = document.querySelectorAll("tr");
let td = document.querySelectorAll("td");
//封装一个方法获得自己是父元素的第几个子元素节点
Object.prototype.index = function () {
var arr = this.parentElement.children
for (let i = 0; i < arr.length; i++) {
if (arr[i] === this) {
return i
}
}
}
for (let i = 0; i < tr.length; i++) {
//获取对应的全部子元素
let td = tr[i].querySelectorAll("td");
for (let j = 0; j< td.length; j++) {
if (j%2==0) {
td[j].style.backgroundColor = "pink";
}
}
}
for (let i = 0; i < td.length; i++) {
td[i].onclick = function () {
// 排他
for (let j = 0; j < td.length; j++) {
td[j].style.backgroundColor = "white";
}
for (let a = 0; a < tr.length; a++) {
let x = this.index();//获取自己是第几个tr
let td = tr[a].querySelectorAll("td");
td[x].style.backgroundColor = "pink";//让那一列变色
}
}
}
结果: