<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #box{ width:150px; height:150px; background-color:red; } </style> </head> <body> <input type="checkbox" id="all"><label for="all">全选</label> <hr> <input type="checkbox" name="check[]" id="nth1"><label for="nth1">选项</label> <input type="checkbox" name="check[]" id="nth2"><label for="nth2">选项</label> <input type="checkbox" name="check[]" id="nth3"><label for="nth3">选项</label> <input type="checkbox" name="check[]" id="nth4"><label for="nth4">选项</label> <input type="checkbox" name="check[]" id="nth5"><label for="nth5">选项</label> <input type="checkbox" name="check[]" id="nth6"><label for="nth6">选项</label> <script> document.getElementById('all').onclick = function(){ var a = document.getElementsByName('check[]'); for(i=0; i<a.length; i++){ if(document.getElementById('all').checked){ a[i].checked = true; }else{ a[i].checked = false; } } } </script> </body> </html>
利用循环和if判断来实现功能