• 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>
  • 相关阅读:
    实用的 jquery 弹出窗口 插件winbox
    软考大纲
    那些年踩过三轮车的程序员
    今天是周几?
    本故事荣获2011年度最佳故事情节奖.
    命令行修改linux时间
    [置顶] 自考,认证相关资料
    金山软件面试题
    del
    【转】数据结构:位图法
  • 原文地址:https://www.cnblogs.com/creazybeauty/p/8063980.html
Copyright © 2020-2023  润新知