hahhhha
监听每个input:checkbox状态改变的事件,然后再获取被勾选的个数。如下:<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="checkbox" name="bobby">0
<input type="checkbox" name="bobby">1
<input type="checkbox" name="bobby">2
<input type="checkbox" name="bobby">3
<input type="checkbox" name="bobby">4
<input type="checkbox" name="bobby">5
<input type="checkbox" name="bobby">6
<input type="checkbox" name="bobby">7
<input type="checkbox" name="bobby">8
<input type="checkbox" name="bobby">9
<br/><br/>
<input type="button" value="全选" onclick="check(true)">
<input type="button" value="全不选" onclick="check(false)">
<h3>选中元素个数<span>0</span>个</h3>
<script>
var bobbyEleList = document.getElementsByName("bobby");
var viewEle = document.getElementsByTagName("span") ;
var bobbyEleArr = [];
//全选或者全不选
function check(status){
bobbyEleArr.map(function(j){
j.checked =status;
});
getCheckedLen();
};
//获取被选中的元素个数
var getCheckedLen=function(){
var checkEle = bobbyEleArr.filter(function(j,i){
if(j.checked==true) return true;
else return false;
});
console.log(checkEle.length);//获取到选中的元素个数
viewEle[0].innerHTML = checkEle.length;
};
//监听元素状态改变事件
bobbyEleList.forEach(function(j,i){
bobbyEleArr.push(j);
j.onchange=function(){
getCheckedLen();
}
});
</script>
</body>
</html>