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 border="1" 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>




發佈了27 篇原創文章 · 獲贊 11 · 訪問量 31萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章