当前位置:软件学堂 > 资讯首页 > 网络编程 > 编程其他 > JS代码实现选中表格行前的复选框则行变色

JS代码实现选中表格行前的复选框则行变色

2012/11/1 16:16:59作者:佚名来源:网络

移动端

【实例名称】

JS代码实现选中表格行前的复选框则行变色

【实例描述】

ASP.NET提供一个网格控件,当用户选择某行时,整行的颜色都会发生变化,但HTML中的表格不具有此特效。本例学习如何通过JaVaScript变通的手法,实现普通表格整行颜色变化的特效。

【实例代码】

<html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>标题页-学无忧(www.xue51.com)</title> </head> <body> <table width="50%"  border="0" cellspacing="0" cellpadding="0" align="center">   <tr>     <td bgcolor="#CC6655"><input type="checkbox" name="checkbox" value="checkbox" onClick="if(this.checked) {this.parentNode.parentNode.style.background='#cc5566'} else{this.parentNode.parentNode.style.background=''}"> 全选</td>   </tr>   <tr>     <td><table id="tab1" width="100%"  border="0" cellspacing="0" cellpadding="0">       <tr>         <td><input type="checkbox" name="checkbox" value="checkbox" onclick="if(this.checked) {this.parentNode.parentNode.style.background='#cc5566'} else{this.parentNode.parentNode.style.background=''}">       第一行</td><td>第二列</td>       </tr>       <tr>         <td><input type="checkbox" name="checkbox" value="checkbox" onclick="if(this.checked) {this.parentNode.parentNode.style.background='#cc5566'} else{this.parentNode.parentNode.style.background=''}">       第二行</td><td>第二列</td>       </tr>     </table></td>   </tr> </table></body> </html>

【运行效果】

JS代码实现选中表格行前的复选框则行变色运行效果

【难点剖析】

本例在表格的第一列中添加了“checkbox”标签,实现复选框效果。当用户选中复选框时,触发其“onclick”事件。“parentNode”表示当前选中元素的父节点,当前元素是“checkbox”,其父节点是“td”标签,因为要求全行都选中,所以还必须再选择上一级父节点“tr”标签,本例使用了“this.parentNode.parentNode”。修改表格行的背景色使用“background”属性。

【源码下载】

如果你不愿复制代码及提高代码准确性,你可以点击:选中表格行前的复选框则行变色 进行本实例源码下载 

标签: 复选框