用JavaScript实现全选-反选
实现全选-反选
在日常生活我们会遇到需要全选-反选的地方,其实用JavaScript也能实现。
样式如下所示:
样式代码如下所示:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>全选-反选</title>
</head>
<body>
<h2>请选择您的兴趣爱好</h2>
<input type="checkbox" value="全选" id="chkAll"/><label for="chkAll">全选</label>
<input type="button" value="反选" id="reverse" />
<ul id="favors">
<li><input type="checkbox" value="" />打篮球</li>
<li><input type="checkbox" value="" />打篮球</li>
<li><input type="checkbox" value="" />看电影</li>
<li><input type="checkbox" value="" />看书</li>
<li><input type="checkbox" value="" />书法</li>
<li><input type="checkbox" value="" />唱歌</li>
<li><input type="checkbox" value="" />徒步旅行</li>
</ul>
</body>
</html>
JavaScript部分如下所示:
function $(id){
return document.getElementById(id);
}
window.onload = function(){
$("chkAll").onclick = function(){
var fvs = $("favors").getElementsByTagName("input");
for (var i = 0; i < fvs.length; i++) {
fvs[i].checked = $("chkAll").checked;
};
}
$("reverse").onclick = function(){
var ipts = $("favors").getElementsByTagName("input");
for (var i = 0; i < ipts.length; i++) {
ipts[i].checked = !ipts[i].checked;
};
}
var fvs = $("favors").getElementsByTagName("input");
for (var i = 0; i < fvs.length; i++) {
fvs[i].onclick = function(){
var isChkAll = true;
for (var i = 0; i < fvs.length; i++) {
if(!fvs[i].checked){
isChkAll = false;
break;
}
};
$("chkAll").checked = isChkAll;
}
};
}