原生js实现复选框的全选反选

<div>
	<table>
		<thead>
			<tr>
				<th><input type="checkbox" id="sales_checkAll"></th>
				<th>商品</th>
				<th>价格</th>
				<th>数量</th>
			</tr>
		</thead>
		<tbody id="sales_tb">
			<tr>
				<td><input type="checkbox"></td>
				<td>vivo</td>
				<td>1999</td>
				<td>200</td>
			</tr>
			<tr>
				<td><input type="checkbox"></td>
				<td>huawei</td>
				<td>1390</td>
				<td>100</td>
			</tr>
			<tr>
				<td><input type="checkbox"></td>
				<td>ipad</td>
				<td>3000</td>
				<td>200</td>
			</tr>
			<tr>
				<td><input type="checkbox"></td>
				<td>iphone</td>
				<td>5000</td>
				<td>200</td>
			</tr>
		</tbody>
	</table>
	<input type="button" id="btn" value="反选">
</div>
div {
	width: 280px;
	margin: 100px auto;
}
table {
	border-collapse: collapse;
	text-align: center;
}
table, th, td {
	border: 1px solid #000;
}
th, td {
	padding: 5px 10px;
}
#btn {
	margin-top: 5px;
}
// 获取全选元素,注册点击事件
var sales_checkAll = document.getElementById('sales_checkAll');
var sales_tb = document.getElementById('sales_tb');
var inputs = sales_tb.getElementsByTagName('input');
// 全选
sales_checkAll.onclick = function () {
	// 找到tbody中的复选框,设置选中属性值与全选一致
	for (var i = 0; i < inputs.length; i++) {
		var input = inputs[i];
		if (input.type === 'checkbox') {  // 找到复选框
			input.checked = this.checked;
		}
	}
}
// tbody中的复选框全不选或者全选时,改变全选复选框的状态
for (var i = 0; i < inputs.length; i++) {  // 外层循环给tbody中的复选框注册点击事件
	var input = inputs[i];
	if (input.type !== 'checkbox') { // 找到复选框
		continue;  // 不再往下执行,继续下一次循环
	}
	input.onclick = function () {  // 点击时才会触发,此时外层循环已经遍历完,此时的input是最后点击的那个
		checkAllChecked();
	}
}
// 判断tbody中的复选框是否被全选  封装成函数  不需要返回值
function checkAllChecked() {
	// 假设所有的checkbox都被选中
	var isAllChecked = true;
	// 判断是否所有的都被选中
	for (var i = 0; i < inputs.length; i++) {
		var input = inputs[i];
		if (input.type !== 'checkbox') { // 找到复选框
			continue;  // 不是复选框的input 不再往下执行,继续下一次循环
		}
		if (!input.checked) {
			isAllChecked = false;
		}
	}
	sales_checkAll.checked = isAllChecked;
}
// 反选
var btn = document.getElementById('btn');
btn.onclick = function () {
	for (var i = 0; i < inputs.length; i++) {
		var input = inputs[i];
		if (input.type !== 'checkbox') { // 找到复选框
			continue;  // 不再往下执行,继续下一次循环
		}
		input.checked = !input.checked;
	}
	checkAllChecked();
}

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值