首页 > 代码库 > 点击表格的单元格时实现变颜色
点击表格的单元格时实现变颜色
<title>无标题文档</title>
<script type="text/javascript" language="javascript">
//清空
function backs(){
var td= document.getElementsByTagName("td");
for(var i=0;i<td.length;i++){
td[i].style.backgroundColor=""; }
}
//浏览器加载时,先把表格的事件先加载好,点击表格时触发
function selectTable(){
var td=document.getElementsByTagName("td");
for(var i=0;i<td.length;i++){
td[i].onclick = function() {
backs();
this.style.background = ‘red‘;
};
}
}
window.onload=selectTable;
</script>
</head>
<body>
<table width="200" border="1">
<tr>
<td>商品名称</td>
<td>数量</td>
<td>价格</td>
<td>合计</td>
</tr>
<tr>
<td onclick="changeBackgound(this)">手机</td>
<td onclick="changeBackgound(this)">1</td>
<td onclick="changeBackgound(this)">888</td>
<td onclick="changeBackgound(this)">888</td>
</tr>
<tr>
<td>手表</td>
<td>1</td>
<td>999</td>
<td>999</td>
</tr>
</table>
</body>