js编写类似购物车checkbox全选反选案例--小技巧

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			window.onload = function() {
				var btn1 = document.getElementById('btn1');
				var btn2 = document.getElementById('btn2');
				var btn3 = document.getElementById('btn3');
				var alls = document.getElementById('alls');
				// console.log(btn1);
				var tf = true;
				//全选/取消
				alls.onclick = function(){
					if(tf){
						for(var i = 0; i < ck.length; i++){
							ck[i].checked = tf;
						}
						// tf = false;
					}else{
						for(var i = 0; i < ck.length; i++){
							ck[i].checked = tf;
						}
						// tf = true;
					}
					tf = !tf;
				}
				
				
				var ck = document.getElementsByName('c1');
				// console.log(ck);
				// 全选
				btn1.onclick = function(){
					for(var i = 0; i < ck.length; i++){
						ck[i].checked = true;
						console.log(ck[i]);
					}
					alls.checked = true;
				}
				//取消
				btn3.onclick = function(){
					for(var i = 0; i < ck.length; i++){
						ck[i].checked = false;
						console.log(ck[i]);
					}
					alls.checked = false;
				}
				//反选
				btn2.onclick = function(){
					for(var i = 0; i<ck.length; i++){
						ck[i].checked = !ck[i].checked;
					}
					alls.checked = false;
				}
				
			}
		</script>
	</head>
	<body>
		<table border="1" cellspacing="" cellpadding="">
			<tr>
				<th><label><input type="checkbox" name="" id="alls" value="" />全选/取消</label></th>
				<th>游戏昵称</th>
				<th>等级</th>
			</tr>
			<tr>
				<td><input type="checkbox" name="c1" id="" value="" /></td>
				<td>小呆呆</td>
				<td>16级</td>
			</tr>
			<tr>
				<td><input type="checkbox" name="c1" id="" value="" /></td>
				<td>小呆</td>
				<td>13级</td>
			</tr>
			<tr>
				<td><input type="checkbox" name="c1" id="" value="" /></td>
				<td>呆呆</td>
				<td>6级</td>
			</tr>
			<tr>
				<td><input type="checkbox" name="c1" id="" value="" /></td>
				<td>小呆呆</td>
				<td>1级</td>
			</tr>
			<tr>
				<td colspan="3">
					<button type="button" id="btn1">全选</button>
					<button type="button" id="btn2">反选</button>
					<button type="button" id="btn3">取消</button>
				</td>
			</tr>
		</table>
	</body>
</html>

 

posted @ 2020-03-19 21:36  JackieDYH  阅读(3)  评论(0编辑  收藏  举报  来源