監(jiān)聽(tīng)每個(gè)input:checkbox狀態(tài)改變的事件,然后再獲取被勾選的個(gè)數(shù)。
如下:
<!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>選中元素個(gè)數(shù)<span>0</span>個(gè)</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();
????????};
????????//獲取被選中的元素個(gè)數(shù)
????????var?getCheckedLen=function(){
????????????var?checkEle?=?bobbyEleArr.filter(function(j,i){??
????????????????if(j.checked==true)??return?true;
????????????????else?return?false;
????????????});
????????????console.log(checkEle.length);//獲取到選中的元素個(gè)數(shù)
????????????viewEle[0].innerHTML?=?checkEle.length;??
????????};
????????//監(jiān)聽(tīng)元素狀態(tài)改變事件
????????bobbyEleList.forEach(function(j,i){
????????????bobbyEleArr.push(j);
????????????j.onchange=function(){
????????????????getCheckedLen();
????????????}
????????});
????</script>
</body>
</html>