1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>原生js - 全选、非全选</title> </head> <body> <div class="wrap"> <label> <input type="checkbox" id="selectAll" /> 全选 </label> <label> <input type="checkbox" class="checkbox" /> 选项1 </label> <label> <input type="checkbox" class="checkbox" /> 选项2 </label> <label> <input type="checkbox" class="checkbox" /> 选项3 </label> <label> <input type="checkbox" class="checkbox" /> 选项4 </label> <label> <input type="checkbox" class="checkbox" /> 选项5 </label> </div> <script> var Roc = { selectAll: document.getElementById("selectAll"), checkboxs: document.getElementsByClassName("checkbox"),
init: function () { this.handleCheck(); }, handleCheck: function () { var that = this; that.selectAll.addEventListener("click", function () { for (let i = 0; i < that.checkboxs.length; i++) { that.checkboxs[i].checked = that.selectAll.checked; } }); for (let i = 0; i < that.checkboxs.length; i++) { that.checkboxs[i].addEventListener("click", function () { let allChecked = true; for (let j = 0; j < that.checkboxs.length; j++) { if (!that.checkboxs[j].checked) { allChecked = false; break; } } that.selectAll.checked = allChecked; }); } }, }; Roc.init(); </script> </body> </html>
|