table单击一列改变样式

本文档介绍了如何在表格中实现单击某一列时改变该列的样式。首先阐述了需求,接着详细讲解了实现这一功能的思路,最后通过具体步骤展示了实际操作过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、需求:

table中单击一列,改变该列的颜色,且原来已经改变过颜色的列恢复原状。

二、思路:

对table中th、td增加onclick方法,获取该列的columnIndex,循环操作每一行(tr)列号为columnIndex元素,改变其style。这里的循环用jquery选择器来操作,非常方便。

三、具体实现:

下面是一个demo。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JavaScript单击table改变某一列的样式</title>
	<script id="jquery_183" type="text/javascript" class="library" src="http://runjs.cn/js/sandbox/jquery/jquery-1.8.3.min.js"></script>
	
<script type="text/javascript">
	var selectedColumn;
 function changeColumnStyle(cell){
		var index = cell.cellIndex;
	 if (typeof selectedColumn != "undefined") {//selectedColumn
		 $('#mytable tr').find(('th')).css({color:''});
		 $('#mytable tr').find(('td')).css({color:''});
	 }
	 selectedColumn = cell;
	 	 
	 $('#mytable tr').find('th:eq(\''+index+'\')').css({color:'red'});	 
	 $('#mytable tr').find('td:eq(\''+index+'\')').css({color:'red'});	 
	  

 }  
</script>
	
	
	
</head>
<body style="width:100%; height:100%;">
<table id="mytable" border="1" width="37%">
	<thead>
	<tr>
		<th width="63" onclick="changeColumnStyle(this)">11</th>
		<th width="68" onclick="changeColumnStyle(this)">12</th>
		<th width="62" onclick="changeColumnStyle(this)">13</th>
		<th width="75" onclick="changeColumnStyle(this)">14</th>
	</tr>
	</thead>
	<tbody>
		<tr>
		<td width="63" onclick="changeColumnStyle(this)">21</td>
		<td width="68" onclick="changeColumnStyle(this)">22</td>
		<td width="62" onclick="changeColumnStyle(this)">23</td>
		<td width="75" onclick="changeColumnStyle(this)">24</td>
	</tr>
	<tr>
		<td width="63" onclick="changeColumnStyle(this)">21</td>
		<td width="68" onclick="changeColumnStyle(this)">22</td>
		<td width="62" onclick="changeColumnStyle(this)">23</td>
		<td width="75" onclick="changeColumnStyle(this)">24</td>
	</tr>
	</tbody>
</table>
</body>
</html>

这里面有几个知识点:
1、如何获取table中单击某一列的列号?
对td增加onclick方法,方法中的this传递dom对象的正好是td(th),td本身有cellIndex指明其列索引号。

2、如何用jquery选择整个table中的某一列,包括th、td?
$('#tableId tr').find('td:eq(columnIndex)');
columnIndex是参数需要转义,直接是数字则不需要。这里还曾犯了一个错误:$('td:eq(2)').css({color:'red'}); $('td:eq(4)').css({color:'red'});  

这样选中的实际上是第2行3列和3行第一列, 这里的td:eq里面的参数实际上不是列号columnIndex,而是表中所有td的索引号从1-N。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值