第一种方式:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Document</title><style>body{color: #000}</style>
<script>
document.write("<ul>");
for (var i = 0; i <20; i++) { 创建20个Li document.write("<li>");document.write('<input type="checkbox" name="ids[]" value="'+i+'">ffffffffff'); input名字要加“[]”这样后端程序取得时候为数组。document.write("</li>");}document.write("</ul>");document.write('<a href="javascript:sall()">全选 </a>'); 此a被点击的时候调用sall方法,此处是调用不是赋值所以要加上“()”。document.write('<a href="javascript:nall()">全不选 </a>');document.write('<a href="javascript:fall()">反选 </a>');var unames=document.getElementsByName("ids[]");function sall(){for(var i=0;i<unames.length;i++){unames[i].checked="true";}}function nall(){for(var i=0;i<unames.length;i++){unames[i].checked="";}}function fall(){for(var i=0;i<unames.length;i++){if(unames[i].checked){unames[i].checked="";}else{unames[i].checked="true";}}}
</script>
</head>
<body>
</body>
</html>
第二种方式:
<script>
document.write("<ul>");
for (var i = 0; i <20; i++) {document.write("<li>");document.write('<input type="checkbox" name="ids[]" value="'+i+'">ffffffffff');document.write("</li>");}document.write("</ul>");document.write('<label for="sall"><input type="checkbox" id="sall" οnclick="sall(this)">全选</label>');this把当前的checkbox对象传递给函数内部方便调用该checkbox对象。var unames=document.getElementsByName("ids[]");
function sall(that){for (var i = 0; i <unames.length; i++) {unames[i].checked=that.checked;}
}
</script>