JavaScript实现全选、全不选、反选功能

效果图
JavaScript实现全选、全不选、反选功能_第1张图片
代码部分:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>全选和反选</title>
		<script type="text/javascript">
			function $(id){
     
				return document.getElementById(id);
			}
			window.onload = function(){
     
				//全选
				$("chkAll").onclick = function(){
     
					var ipts = $("favors").getElementsByTagName("input");
					for (var i = 0; i < ipts.length; i++) {
     
						ipts[i].checked = $("chkAll").checked;
					}
				}
				
				//反选
				$("reverse").onclick = function(){
     
					var res = $("favors").getElementsByTagName("input");
					for (var i = 0; i < res.length; i++) {
     
						res[i].checked = !res[i].checked;
					}
				}
				
				//使全选框和下面各个兴趣框同步
				var fvs = $("favors").getElementsByTagName("input");
				for (var i = 0; i < fvs.length; i++) {
     
					fvs[i].onclick = function(){
     
						var isCheckAll = true;
						for (var j = 0; j < fvs.length; j++) {
     
							if (!fvs[j].checked) {
     
								isCheckAll = false;
								break;
							}
						}
						$("chkAll").checked = isCheckAll;
					}
				}
				
			}
		</script>
	</head>
	<body>
		<h1>你的兴趣是什么?</h1>
		<input type="checkbox" id="chkAll" value="全选" /> <label for="chkAll">全选</label>
		<input type="button"  id="reverse" value="反选" />
		<p></p>
		<div id="favors">
			<input type="checkbox">Python
			<input type="checkbox">Java
			<input type="checkbox">JavaScript
			<input type="checkbox">C#
			<input type="checkbox">C++
		</div>
	</body>
</html>

你可能感兴趣的:(前端,JavaScript,反选和全选)