技术协助请求:根据数值设置表格CPU与Memory Utilization单元格背景色
问题分析与修复方案
原代码的核心问题
document.getElementsByTagName("td")返回的是所有<td>元素的集合,不能直接访问innerHTML(注意拼写错误:正确写法是innerHTML而非innerHtml)- 未筛选目标列,会错误修改所有单元格的背景色,不符合仅处理CPU_Utilization和Memory_Utilization列的需求
- 直接用字符串与数字比较,会导致逻辑判断失效(比如字符串"78"和数字50的比较逻辑不符合预期)
- 未遍历目标单元格,仅尝试操作元素集合本身,无法对单个单元格生效
修复后的完整代码
<!DOCTYPE html> <html> <head> <style> table, th, td { border: 1px solid black } </style> </head> <body> <h2>Table With Border</h2> <p>Use the CSS border property to add a border to the table.</p> <table style="width:100%"> <tr> <th>Snaplex_name</th> <th>Node_name</th> <th>CPU_Utilization</th> <th>Memory_Utilization</th> <th>Version</th> <th>Status</th> </tr> <tr> <td>Server1</td> <td>Serverd01</td> <td>78</td> <td>25</td> <td>4.31</td> <td>up_and_running</td> </tr> <tr> <td>Server1</td> <td>serverd01</td> <td>60</td> <td>75</td> <td>4.31</td> <td>up_and_running</td> </tr> </table> <script> // 获取所有非表头的表格行 const rows = document.querySelectorAll('table tr:not(:first-child)'); rows.forEach(row => { // 定位CPU和Memory列的单元格(索引从0开始,对应第3、4列) const cpuCell = row.children[2]; const memoryCell = row.children[3]; // 封装背景色设置逻辑 const setCellBg = (cell) => { const value = parseInt(cell.textContent); if (value <= 50) { cell.style.backgroundColor = 'green'; } else if (value <= 75) { cell.style.backgroundColor = 'yellow'; } else { cell.style.backgroundColor = 'red'; } }; // 处理两个目标单元格 setCellBg(cpuCell); setCellBg(memoryCell); }); </script> </body> </html>
修复说明
- 用
querySelectorAll精准筛选非表头行,避免误处理表头 - 通过索引定位目标列单元格,确保仅修改CPU和Memory利用率对应的单元格
- 使用
parseInt将单元格文本转为数字,保证数值比较逻辑正确 - 封装重复逻辑为函数,提升代码可读性和可维护性
- 改用
textContent获取单元格内容,避免HTML结构干扰判断
内容的提问来源于stack exchange,提问作者Manoj D
相关产品推荐
相关产品推荐

