JS实现复选框全选功能

Original 2019-01-31 10:26:46 266
abstract:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>JS实现复选框全选功能</title><style>.box{padding: 0;margin: 80px auto;width:300px;

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>JS实现复选框全选功能</title>

<style>

.box{

padding: 0;

margin: 80px auto;

width:300px;

border: 1px solid rgb(213, 223, 231);

border-radius: 5px 5px 0 0 ;

}

.box .ck{

height:40px;

color:#fff;

line-height: 20px;

background: rgba(18, 114, 192, .85);

border-radius: 5px 5px 0 0 ;

}

.ck input{

margin: 10px;

}

.cont input{

margin:  10px;

}

</style>

</head>

<body>

<div class="box">

<div class="ck">

<input type="checkbox" id="all" onclick="check()">全选

</div>

<div class="cont">

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

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

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

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

</div>

</div>

<script>

function check() {

var checkall, item;

//获取到全选复选框的元素

checkall = document.getElementById('all')

//获取到下面子复选项框的元素

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

//根据全选框的状态,用For循环检查子复选项的状态,实现全选功能

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

if (checkall.checked) {

item[i].checked = true

} else {

item[i].checked = false

}

}

}

</script>

</body>

</html>


Correcting teacher:西门大官人Correction time:2019-01-31 10:43:02
Teacher's summary:代码逻辑是正确的,但是还是要注意一下代码的书写的规范。每行代码后面加上分号

Release Notes

Popular Entries