如何实现勾选Checkbox时变更表格中特定TD的背景颜色?
实现勾选Checkbox时高亮对应TD区域
给你一套直接能用的实现方案,核心是通过监听Checkbox状态变化,定位到对应分组的TD并切换高亮样式:
1. 修复HTML结构(移除重复ID)
原代码里多个TD用了相同的id="first",这不符合HTML规范(ID必须唯一),先把重复ID去掉,后续靠DOM位置关系定位目标TD:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link type="text/css" rel="stylesheet" href="views/css/index.css"> </head> <body> <table id="myTable"> <tr> <th>1</th> <th>2</th> <th>3</th> <th>4</th> <th>5</th> <th>6</th> <th>7</th> <th>8</th> <th>9</th> </tr> <% for(let a = 0; a < 10; a ++){ %> <tr> <td>X</td> <td>X</td> <td><input type="checkbox"></td> <td>X</td> <td>X</td> <td><input type="checkbox"></td> <td>X</td> <td>X</td> <td><input type="checkbox"></td> </tr> <% } %> </table> <script src="views/js/index.js"></script> </body> </html>
2. 编写JavaScript逻辑
给每个Checkbox绑定change事件,根据它所在的TD位置,找到对应的两个目标TD,切换高亮类:
// 拿到表格里所有的checkbox const checkboxes = document.querySelectorAll('#myTable input[type="checkbox"]'); // 逐个绑定事件 checkboxes.forEach(checkbox => { checkbox.addEventListener('change', function() { // 找到当前checkbox所在的行 const row = this.closest('tr'); // 算出当前checkbox所在td在该行的位置索引(从0开始算) const tdIndex = Array.from(row.children).indexOf(this.parentElement); let targetTdIndices = []; // 根据checkbox的位置,确定要高亮的td索引 if (tdIndex === 2) { // 第三列的checkbox,对应前两个td(第1、2列) targetTdIndices = [0, 1]; } else if (tdIndex === 5) { // 第六列的checkbox,对应第4、5列的td targetTdIndices = [3, 4]; } else if (tdIndex === 8) { // 第九列的checkbox,对应第7、8列的td targetTdIndices = [6, 7]; } // 给目标td切换高亮样式 targetTdIndices.forEach(index => { const targetTd = row.children[index]; // 勾选时加selected类,取消时移除 targetTd.classList.toggle('selected', this.checked); }); }); });
3. CSS样式保持不变(可按需调整颜色)
table { width: 100%; border-collapse: collapse; } th { width: 10%; } td { text-align: center; border: 1px solid black; } .selected { background: red; }
简单解释
- 用
closest('tr')快速找到当前Checkbox所在的行,避免遍历整个表格 - 通过
Array.from(row.children).indexOf()拿到当前TD在该行的位置,以此判断对应哪组TD需要高亮 classList.toggle()可以直接根据Checkbox的勾选状态,自动添加或移除高亮类,不用写额外的if-else判断
这样操作时,勾选第三列的Checkbox,该行前两个TD就会变红;勾选第六列,第4、5列TD变色;勾选第九列,第7、8列TD变色,完全符合你要的效果。
内容的提问来源于stack exchange,提问作者Xylex
相关产品推荐
相关产品推荐

