<script>
window.onload = function () {
var myTd = document.getElementsByTagName("td");
var currentlyHighlightedRow = null; // 用于存储当前高亮显示的行for (var i = 0; i < myTd.length; i++) {
myTd[i].onclick = function () {
// 获取当前点击的单元格的父节点(即行)
var myTdParent = this.parentNode;// 如果已经有高亮显示的行,则取消其高亮
if (currentlyHighlightedRow) {
currentlyHighlightedRow.style.backgroundColor = "";
}// 将当前点击的行设置为高亮显示
myTdParent.style.backgroundColor = "red";// 更新当前高亮显示的行
currentlyHighlightedRow = myTdParent;
};
}
}
</script>//创建3*3表格
<table border="1" cellspacing="0" cellpadding="0">
<tr>
<td>Data1</td>
<td>Data2</td>
<td>Data3</td>
</tr>
<tr>
<td>Data4</td>
<td>Data5</td>
<td>Data6</td>
</tr>
<tr>
<td>Data7</td>
<td>Data8</td>
<td>Data9</td>
</tr>
</table>