【JavaScript-练习】全选、全不选、反选
程序员文章站
2022-03-25 16:49:30
...
使用纯JS完成全选、全不选、反选功能
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>03-全选全不选反选.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript">
window.onload = function () {
<!-- 全选-->
var checkAll = document.getElementById("checkAll");
checkAll.onclick = function () {
var itemsList = document.getElementsByName("items");
for (var i=0; i < itemsList.length; i++){
itemsList[i].checked = true;
}
var allOrNo = document.getElementById("input");
allOrNo.checked = true;
}
// 全不选
document.getElementById("checkAllNo").onclick = function () {
var itemsList = document.getElementsByName("items");
for (var i=0; i < itemsList.length; i++){
itemsList[i].checked = false;
}
var allOrNo = document.getElementById("input");
allOrNo.checked = false;
}
// 反选
document.getElementById("check_Reverse").onclick = function () {
var itemsList = document.getElementsByName("items");
var checkAllNum = 0;
var allOrNo = document.getElementById("input");
for (var i=0; i < itemsList.length; i++){
itemsList[i].checked = !itemsList[i].checked;
}
// 特殊情况进行判断:
for(var i = 0; i < itemsList.length; i++){
if(itemsList[i].checked == true){
checkAllNum++;
}
}
if (checkAllNum == itemsList.length){
allOrNo.checked = true;
}else{
allOrNo.checked = false;
}
}
//给每个按钮绑定单击事件,
function test() {
var input = document.getElementById("input");
var items = [...document.getElementsByName("items")];
items.forEach((v, i)=>{
v.onchange = function () {
input.checked = items.every(p=>p.checked);
}
});
}
test();
}
</script>
</head>
<body>
您的爱好很广泛!!!
<br>
<input type="checkbox" id="input" />全选/全不选
<input type="checkbox" name="items" value="足球" />足球
<input type="checkbox" name="items" value="篮球" />篮球
<input type="checkbox" name="items" value="游泳" />游泳
<input type="checkbox" name="items" value="唱歌" />唱歌
<br>
<input type="button" name="checkall" id="checkAll" value="全选" />
<input type="button" name="checkall" id="checkAllNo" value="全不选" />
<input type="button" name="checkall" id="check_Reverse" value="反选" />
</body>
</html>
上一篇: PS 没有 PNG 格式怎么办?
下一篇: PHP运算符的实例讲解