JavaScript实现简单的按钮选择
功能分析:四个按钮,全选,全不选,全选和全不选结合,反选。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>按钮练习</title>
<script>
window.onload = function () {
let cbs = document.getElementsByName("cb");
//全选
let bt1 = document.getElementById("bt1");
bt1.onclick = function () {
//循环遍历,把状态变为选中
for (let i = 0; i < cbs.length; i++) {
cbs[i].checked=true;
}
bt3.checked=true;
}
//全不选
let bt2 = document.getElementById("bt2");
bt2.onclick = function () {
//循环遍历,把状态变为不选
for (let i = 0; i < cbs.length; i++) {
cbs[i].checked=false;
}
bt3.checked=false;
}
//全选/全不选
let bt3 = document.getElementById("bt3");
let X=0;//偶数全不选,奇数全选
document.getElementById("bt3").onclick=function () {
let cbs=document.getElementsByName("cb");
X++;
for (let i = 0; i < cbs.length; i++) {
if (X%2==0){
cbs[i].checked=false;
}else {
cbs[i].checked=true;
}
}
}
//反选
let bt4 = document.getElementById("bt4");
bt4.onclick = function () {
bt3.checked = true;
//循环遍历,把状态变为相反的
for (let i = 0; i < cbs.length; i++) {
cbs[i].checked=!cbs[i].checked;
if(!cbs[i].checked){
//一旦进入判断,则证明不是全选状态
//将checkedAllBox设置为没选中状态
bt3.checked = false;
}
}
}
}
</script>
</head>
<body>
<table border="1px" cellspacing="0" cellpadding="10px">
<caption>购物车</caption>
<tr>
<th></th>
<th>商品编号</th>
<th>商品名</th>
<th>商品价格</th>
<th>商品状态</th>
</tr>
<tr>
<td><input type="checkbox" name="cb"></td>
<td>1</td>
<td>运动鞋</td>
<td>399</td>
<td>未发货</td>
</tr>
<tr>
<td><input type="checkbox" name="cb"></td>
<td>2</td>
<td>鼠标</td>
<td>45</td>
<td>已发货</td>
</tr>
<tr>
<td><input type="checkbox" name="cb"></td>
<td>3</td>
<td>医用口罩</td>
<td>56</td>
<td>未发货</td>
</tr>
<tr>
<td><input type="checkbox" name="cb"></td>
<td>4</td>
<td>小米手机</td>
<td>2599</td>
<td>已发货</td>
</tr>
</table>
<div>
<input type="button" id="bt1" value="全选">
<input type="button" id="bt2" value="全不选">
<input type="button" id="bt3" value="全选/全不选">
<input type="button" id="bt4" value="反选">
</div>
</body>
</html>