js实现全选

Original 2019-05-28 09:42:18 215
abstract:<!DOCTYPE html><html><head>    <meta charset="UTF-8" />    <title>全选</title></head><style type="text/css"> 

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8" />

    <title>全选</title>

</head>

<style type="text/css">

    .box{width:100px;height:250px;border:1px solid #ccc; border-radius:10px;margin:20px auto;text-align:center;padding:5px 10px;} 

    .box div{border-bottom:1px solid #ccc;padding-bottom:10px;margin-bottom: 8px;}

    .box input{margin:8px;}   

</style>

<body>

    <div>

        <div>

           <input type="checkbox" id="checkall" onclick="checkAll()"><label for="checkall">全选</label> 

        </div>

        <input type="checkbox" name="item[]">选项1<br>

        <input type="checkbox" name="item[]">选项2<br>

        <input type="checkbox" name="item[]">选项3<br>

        <input type="checkbox" name="item[]">选项4<br>

        <input type="checkbox" name="item[]">选项5<br>

        <input type="checkbox" name="item[]">选项6<br>

        <input type="checkbox" name="item[]">选项7<br>

    </div>

</body>

<script>

    function checkAll(){

        var checkall,item;

        checkall = document.getElementById('checkall');

        item = document.getElementsByName("item[]");

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

            if(checkall.checked){

                item[i].checked = true;

            }else{

                item[i].checked = false;

            }

        }

    }

</script>

</html>


Correcting teacher:天蓬老师Correction time:2019-05-28 15:47:08
Teacher's summary:for(var i=0;i<item.length;i++), 推荐另一种更好的语法 for(var i=0, n = item.length;i<n;i += 1), 这样效率能提升至少10倍

Release Notes

Popular Entries