<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>全选反选示例</title> <script> function selectAll() { var checkboxes = document.querySelectorAll('input[type="checkbox"]'); for (var i = 0; i < checkboxes.length; i++) { checkboxes[i].checked = true; } } function deselectAll() { var checkboxes = document.querySelectorAll('input[type="checkbox"]'); for (var i = 0; i < checkboxes.length; i++) { checkboxes[i].checked = false; } } function toggleSelect() { var checkboxes = document.querySelectorAll('input[type="checkbox"]'); for (var i = 0; i < checkboxes.length; i++) { checkboxes[i].checked = !checkboxes[i].checked; } } </script> </head> <body> <h1>全选反选示例</h1> <input type="checkbox" id="checkbox1"> <label for="checkbox1">选项1</label><br> <input type="checkbox" id="checkbox2"> <label for="checkbox2">选项2</label><br> <input type="checkbox" id="checkbox3"> <label for="checkbox3">选项3</label><br> <button onclick="selectAll()">全选</button> <button onclick="deselectAll()">取消选择</button> <button onclick="toggleSelect()">反选</button> </body> </html>
selectAll()
函数将所有复选框都设置为被选中(全选)。deselectAll()
函数将所有复选框都取消选中(取消选择)。toggleSelect()
函数会将所有复选框的选中状态进行反转(反选)。