zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    二维数组最大子数组算法
    寻找最大子数组
    最大值bug 调试
    多路电梯调度算法
    分析一个文本文件各个词出现的频率,并把频率最高的十个词打印出来。
    使用redis实现生产者消费者模式
    简单使用redis实现sso单点登录
    MongoDB批量导入及简单的性能优化
    mysql安装
    字符串操作性能优化
  • 原文地址:https://www.cnblogs.com/creazybeauty/p/8063980.html
Copyright © 2011-2022 走看看