JS之全选和反选

<body>
<div class="wrap">
<table border="1">
  <thead>
<tr>
<th><input type="checkbox" name="1" id="theadInp"></th>
<th>菜名</th>
<th>饭店</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td><input type="checkbox"></td>
<td>西红柿炒鸡蛋</td>
<td>大味道</td>
</tr>
<tr>
<td><input type="checkbox" ></td>
<td>铁锅鲶鱼</td>
<td>大味道</td>
</tr>
<tr>
<td><input type="checkbox" ></td>
<td>黄瓜炒鸡蛋</td>
<td>大味道</td>
</tr>
<tr>
<td><input type="checkbox" ></td>
<td>拔丝地瓜</td>
<td>大味道</td>
</tr>
</tbody>
</table>
</div>

<script type="text/javascript">
window.onload = function(){
    //需求1:点击了上边的input,下面全选或者反选
    //需求2:获取了上面的input按钮,只要判断,checked属性是true还是false
    var topInp = document.getElementById("theadInp");
    var tbody = document.getElementById("tbody");
    var botInpArr = tbody.getElementsByTagName("input");
    //绑定事件
    topInp.onclick = function(){

// if (topInp.checked===true) {
// for (var i = 0; i < botInpArr.length; i++) {
// botInpArr[i].checked=true;
// }
// }else{
// for (var i = 0; i < botInpArr.length; i++) {
// botInpArr[i].checked=false;
// }
// }

for(var i=0;i<botInpArr.length;i++){

botInpArr[i].checked = this.checked;

}

//需求2:点击下面的input,如果下面的全部选定了,上面的全选,否则相反
//思路:为下面的每个input绑定事件,每点击一次都判断所有的按钮checked属性值是否全部都是true,如果有一个是false,那么上面的input的checked属性也是false

for(var i=0;i<botInpArr.length;i++){
botInpArr[i].onclick() = function(){
//开闭元素
var bool=true;
for(var j=0;j<botInpArr.length;j++){
if(botInpArr[j].checked ===false){
bool=false;
}
}
topInp.checked = bool;
}
} } }
</script> </body>

 

posted @ 2017-12-19 09:43  乖乖乖码  阅读(288)  评论(0编辑  收藏  举报