一、代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button id="all">全選</button>
<button id="reverse">反選</button>
<button id="cancel">取消</button>
<table border="1">
<thead>
<tr>
<th>
<th>姓名</th>
<th>愛好</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>鄉村教師代言人</td>
<td>淘寶、阿里、蜂鳥</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>奶茶妹</td>
<td>商城、金融</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>董老闆</td>
<td>讓世界愛上中國選</td>
</tr>
</tbody>
</table>
<script src="jquery-3.4.1.js" type="text/javascript"></script>
<script>
// 點擊全選按鈕 選中所有的checkbox
// DOM綁定事件方法
// $("#all")[0].onclick = function(){}
// jQuery綁定事件方法
$("#all").click(function () {
$(":checkbox").prop('checked', true);
});
// 取消
$("#cancel").on("click", function () {
$(":checkbox").prop('checked', false);
});
// 反選
$("#reverse").click(function () {
var $checkbox = $(":checkbox");
for (var i=0;i<$checkbox.length;i++){
// 獲取原來的選中與否的狀態
var status = $($checkbox[i]).prop('checked');
$($checkbox[i]).prop('checked', !status);
//此處取反
}
})
</script>
</body>
</html>
二、運行效果