如何使用JavaScript为HTML表格中符合条件的内容动态设置背景色
表格角色筛选高亮实现方案
前置样式准备
先在你的CSS文件或者style标签中加入高亮类,可根据需求自定义样式:
/* 无载具角色高亮样式 */ .no-vehicle { background-color: #fff3cd; } /* 身高最矮角色高亮样式 */ .short-height { background-color: #f8d7da; } /* 若只需要高亮名称单元格,可把类加在nameCell上,对应样式调整为: */ /* .name-highlight { background-color: #d4edda; } */
修改后完整JavaScript代码
const urlFetch = 'https://swapi.dev/api/people/'; /*fetch请求地址*/ let tableWrite = document.getElementById('table-content'); const fetchAPI = async () => { // 拉取数据函数 try { const response = await fetch(urlFetch); const data = await response.json(); const roleList = data.results; // 先计算身高最矮的两个角色:先转数字再排序,过滤掉身高为unknown的无效数据 const sortedByHeight = [...roleList] .filter(item => !isNaN(Number(item.height))) .sort((a, b) => Number(a.height) - Number(b.height)); const shortestTwoNames = sortedByHeight.slice(0,2).map(item => item.name); roleList.forEach(result => { // 创建行和单元格 const row = tableWrite.insertRow(-1); let nameCell = row.insertCell(-1); let eyeColorCell = row.insertCell(-1); let heightCell = row.insertCell(-1); let birthYearCell = row.insertCell(-1); let vehiclesCell = row.insertCell(-1); // 填充单元格内容 nameCell.appendChild(document.createTextNode(result.name)); eyeColorCell.appendChild(document.createTextNode(result.eye_color)); heightCell.appendChild(document.createTextNode(result.height)); birthYearCell.appendChild(document.createTextNode(result.birth_year)); vehiclesCell.appendChild(document.createTextNode(result.vehicles.length)); // 高亮逻辑:无载具的角色 if (result.vehicles.length === 0) { row.classList.add('no-vehicle'); // 若只高亮名称单元格改为:nameCell.classList.add('no-vehicle') } // 高亮逻辑:身高最矮的两个角色 if (shortestTwoNames.includes(result.name)) { row.classList.add('short-height'); // 若只高亮名称单元格改为:nameCell.classList.add('short-height') } }); } catch { console.log('发生错误!'); } finally { console.log("数据拉取完成!"); } } fetchAPI();
核心改动说明
- 拉取到全量角色数据后,先对身高做排序计算,提前筛选出需要高亮的身高最矮的两个角色名单,避免渲染时重复计算
- 每个角色行渲染完成后,直接根据规则匹配添加对应高亮类即可,后续如果要新增其他高亮规则,只需要加对应的类和判断条件即可
内容的提问来源于stack exchange,提问作者zdravko93
相关产品推荐
相关产品推荐

