天天看點

JQuery應用案例--全選與反選

用JQuery實作全選與反選功能。不過下面代碼中實作的反選功能對全選有影響,尚未找到解決辦法,如下圖:

JQuery應用案例--全選與反選

代碼:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
	<meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="../js/jquery-1.8.2.js"></script>
  </head>
  <body>
	<table  align="center">
		<tr>
			<th>狀态</th>
			<th>使用者名</th>
		</tr>
		<tr>
			<td><input type="checkbox"/></td>
			<td>趙</td>
		</tr>
		<tr>
			<td><input type="checkbox"/></td>
			<td>錢</td>
		</tr>		
		<tr>
			<td><input type="checkbox"/></td>
			<td>孫</td>
		</tr>	
		<tr>
			<td><input type="checkbox"/></td>
			<td>李</td>
		</tr>
		<tr>
			<td><input type="checkbox"/></td>
			<td>周</td>
		</tr>	
		<tr>
			<td>
				<input type="checkbox"/>全選
			</td>
			<td><input type="button" value="全反選"/></td>
		</tr>		
	</table>
	
	<script type="text/javascript">
		
		$(":checkbox:last").click(function(){
			//全選
			if($(":checkbox:last").is(":checked")){
				$(":checkbox:not(:last)").attr("checked","checked");
			}else{
				$(":checkbox:not(:last)").removeAttr("checked","checked");
			}
		});
		
		//反選
		
		$(":button").click(function(){
			//方式一
			$(":checkbox").not(":checkbox:last").each(function(){
				if($(this).is(":checked")){
					$(this)	.removeAttr("checked","checked");
				}else{
					$(this).attr("checked","checked");
				}
			});	
		
			/*
			//方式二
			//将已經選中的複選框失效
			$(":checkbox:checked").attr("disabled","disabled");
			//将剩下的未選中的複選框選中
			$(":checkbox:not(:checked)").attr("checked","checked");
			//将失效的複選框生效
			$(":checkbox:disabled").removeAttr("disabled","disabled").removeAttr("checked","checked");
			*/	
			
		});
		
	</script>
  </body>
</html>