太久没写原生js了,过程中遇到了个问题就是 通过document.getElementsByClassName获取到的是所有为此类名的元素,所以不能直接给他注册点击事件,要通过数组的方式,通过下标来确定元素
代码参考网址我给关了。。。就不贴了
效果图
代码如下
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>
<button class="checkAll">全选</button>
<button class="notCheck">反选</button>
</div>
<div>
<ul>
<li>1<input type="checkbox"></li>
<li>2<input type="checkbox"></li>
<li>3<input type="checkbox"></li>
<li>4<input type="checkbox"></li>
<li>5<input type="checkbox"></li>
</ul>
</div>
</body>
<script>
window.onload = function () {
var checkAll = document.getElementsByClassName("checkAll");
console.log(checkAll)
var notCheck = document.getElementsByClassName("notCheck");
var inputs = document.getElementsByTagName("input")
console.log(inputs)
function check(flag) {
for (var i = 0;i < inputs.length;i++) {
inputs[i].checked = flag
}
}
console.log(222)
checkAll[0].onclick = function () {
console.log(123)
check(true)
}
notCheck[0].onclick = function () {
for (var i = 0;i < inputs.length;i++) {
inputs[i].checked = !inputs[i].checked
}
}
}
</script>
</html>