好看的颜色库存:
#d0e4fe
lightblue
lightgreen
好看的字体库存 font-family:
"Times New Roman"
示例功能:
1. 点击总的全选复选框,选中页面中所有的复选框
2. 点击”作者“的复选框,能够选中其所属”书本“的复选框
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>checkbox的全选功能</title>
<style>
table thead{
background-color: #d0e4fe;
}
table tbody{
background-color: lightgreen;
}
</style>
</head>
<body>
<table align="center">
<thead>
<tr>
<th style="width: 30px;" align="center">
<!-- 总体的checkbox -->
<input type="checkbox" name="" id="checkbox-all">
</th>
<th style="width: 150px;" align="center">Content</th>
</tr>
</thead>
<tbody>
<!-- 作者用id -->
<!-- 1 作者 -->
<tr id="author-1-item" align="center">
<td><input type="checkbox" class="author-checkbox"></td>
<td>余华</td>
</tr>
<!-- 其书本用class, 其中author的id值===book的class值 -->
<tr class="author-1-item" align="center">
<td><input type="checkbox" class="book-checkbox"></td>
<td>《活着》</td>
</tr>
<tr class="author-1-item" align="center">
<td><input type="checkbox" class="book-checkbox"></td>
<td>《许三观卖血记》</td>
</tr>
<!-- 2 作者 -->
<tr id="author-2-item" align="center">
<td><input type="checkbox" class="author-checkbox"></td>
<td>曹文轩</td>
</tr>
<!-- 其书本用class, 其中author的id值===book的class值 -->
<tr class="author-2-item" align="center">
<td><input type="checkbox" class="book-checkbox"></td>
<td>《草房子》</td>
</tr>
<tr class="author-2-item" align="center">
<td><input type="checkbox" class="book-checkbox"></td>
<td>《青铜葵花》</td>
</tr>
</tbody>
</table>
<script>
// 一. author的复选框选中,选中其所属的boox的复选框
//1. 获取所有author的复选框
let authors = document.querySelectorAll('.author-checkbox');
//2. 为每个author的复选框添加点击事件
authors.forEach(person => {
person.addEventListener('click', ()=> {
//2.1 获取author的checkbox所属的tr
let authorRow = person.closest('tr');
let class_id = authorRow.id; //将author的id值暂存下来
//2.2 获取author所有的book的tr author的id值===book的class值
let bookRows = authorRow.parentNode.querySelectorAll(`tr[class="${class_id}"]`);
//2.3 author的checkbox选中,则让book的checkbox选中; author的checkbox取消选中,则让book的checkbox取消选中
bookRows.forEach(book =>{
book.querySelector('.book-checkbox').checked = person.checked;
})
})
})
// 二.点击总的复选框,选中页面全部checkbox(author + book)
//1. 获取复选框
let all = document.getElementById('checkbox-all');
//2. 给复选框添加点击事件的监听器
all.addEventListener('click', () => {
let authors = document.querySelectorAll('.author-checkbox');
let books = document.querySelectorAll('.book-checkbox');
authors.forEach(author => {
author.checked = all.checked;
})
books.forEach(book => {
book.checked = all.checked;
})
})
</script>
</body>
</html>
运行如下: