HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>操作复选框</title>
<link rel="stylesheet" href="css/index.css" />
<script type="text/javascript" src="js/index.js" ></script>
<script type="text/javascript" src="js/jquery-2.1.0.js" ></script>
</head>
<body>
<div id="hobby">
您喜欢做的事情:
<div>
<input id="basketball" type="checkbox" name="basketball" />篮球
</div>
<div>
<input id="tv" type="checkbox" name="tv" />看电视
</div>
<div>
<input id="internet" type="checkbox" name="internet" />上网
</div>
<div>
<input id="book" type="checkbox" name="book" />看书
</div>
<div>
<input id="tour" type="checkbox" name="tour" />旅游
</div>
<div>
<input id="music" type="checkbox" name="music" />听音乐
</div>
<div>
<input id="others" type="checkbox" name="others" />其他
</div>
</div>
<div id="buttonGroup">
<div class="button">
<button id="selectAll" οnclick="selectHobby(1)">全选</button>
</div>
<div class="button">
<button id="selectNone" οnclick="selectHobby(0)">全不选</button>
</div>
<div class="button">
<button id="selectInvert" οnclick="selectHobby(-1)">反选</button>
</div>
</div>
</body>
</html>
JS
//获取所有喜欢做的事情
function getHobby(selector){
return $(selector);
}
//绑定行
function bindRaw(){
$("#hobby div").each(function (){
$(this).on('click', function (){
var inputId = $($(this)[0].children[0].outerHTML).attr("id");
$("#"+inputId).prop("checked", !$("#"+inputId).prop("checked"));
})
})
}
window.addEventListener('load', getHobby, false);
window.addEventListener('load', bindRaw, false);
//按钮触发事件
function selectHobby(type){
console.debug(type);
var selector = "input";
var inputs = getHobby(selector);
inputs.each(function all(){
if (type < 0){
$(this).prop("checked", !$(this).prop("checked"));
}else{
$(this).prop("checked", type);
}
});
}
CSS
#hobby{
margin-bottom: 10px;
}
#hobby div{
cursor: pointer;
width: 100px;
}
.button{
display: inline;
cursor: pointer;
}
.button button{
border-radius: 10px;
}
BUG 修复
bindRaw()方法修改:
//绑定行
function bindRaw(){
$("#hobby div span").each(function (){
$(this).on('click', function (){
var inputId = $(this)[0].previousSibling.id;
$("#"+inputId).prop("checked", !$("#"+inputId).prop("checked"));
})
})
}
<input id="book" type="checkbox" name="book" />看书
修改为
<input id="book" type="checkbox" name="book" /><span>看书</span>