应用场景: 当我们限制多选框选择数量时用到
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/072e1a7454e9ddfa29567342c63efd7e.png)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="checkbox" name="ball" id="">足球
<input type="checkbox" name="ball" id="">篮球
<input type="checkbox" name="ball" id="">排球
<input type="checkbox" name="ball" id="">羽毛球
<input type="checkbox" name="ball" id="">乒乓
<p>选择(最多三项)</p>
<script>
var ipts = document.querySelectorAll("input");
console.log(ipts);
for (var j = 0; j < ipts.length; j++) {
ipts[j].onclick = function() {
var count = 0;
for (var i = 0; i < ipts.length; i++) {
console.log(ipts.checked);
if (ipts[i].checked == true) {
count++;
}
}
if (count > 3) {
alert('只能选三个');
return false;
}
}
}
</script>
</body>
</html>