<table id="tb">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
</table>
<script>
var td = document.getElementsByTagName('td');
// console.log(td);
for (var a in td) { (a约等于for循环的名称,引用时放在[]中,不能再忘记了)
td[a].onclick = function () {
// this.style.backgroundColor='red';(点击颜色不消失)
if (this.style.backgroundColor) {
this.style.backgroundColor = ""
}
else {
this.style.backgroundColor = "red"
}
}
}
<----------------------------------------------------鼠标移上去变色移走颜色还原---------------------------------------------------------------->
(用到两个方法)
var td=document.getElementsByTagName('td');
for(var i in td){
td[i].onmouseover=function(){
this.style.backgroundColor="red";}
}
for(var i in td){
td[i].onmouseout=function(){
this.style.backgroundColor="";}
}