本文实例为大家分享了JavaScript实现页面一键全选或反选的具体代码,供大家参考,具体内容如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.hobby {
width: 600px;
height: 50px;
background-color: #5F9EA0;
line-height: 50px;
}
.but {
float: right;
margin-right: 10px;
}
</style>
</head>
<body>
<div class="hobby">
<!-- 创建多选框 -->
<input type="checkbox" checked="true" name="hobby" id="" value="羽毛球" />羽毛球
<input type="checkbox" name="hobby" id="" value="赛车" />赛车
<input type="checkbox" name="hobby" id="" value="听音乐" />听音乐
<input type="checkbox" name="hobby" id="" value="看杂志" />看杂志
<!-- 选择按钮 -->
<div class="but">
<button type="button" onclick="selectAll(this)">全选</button>
<button type="button" onclick="selectAllOut()">全不选</button>
</div>
</div>
<script type="text/javascript">
// 全选方法
function selectAll(obj) {
var a = document.getElementsByName("hobby");
for (var i = 0; i < a.length; i++) {
a[i].checked = "true";
console.log(a[i].value)
}
};
// 全部取消方法
function selectAllOut() {
var a = document.getElementsByName("hobby");
for (var i = 0; i < a.length; i++)
a[i].checked = "";
}
</script>
</body>
</html>