根据Fetch返回值修改元素背景色时遇TypeError问题求助
问题概述
尝试根据Fetch接口返回的结果修改元素背景色:当返回数值大于1时设为绿色,为0时设为红色。但运行时持续报错:TypeError: Cannot read properties of null (reading 'style')
原代码
JavaScript
const pegsData_url = "https://fakestoreapi.com/products"; const uiProgressBar = document.querySelector(`.${name}-bar-fill`); const pegs1 = document.getElementById("total-time-1"); async function isActive(){ const response = await fetch(pegsData_url) const data = await response.json(); console.log(data); if(data[1].price >= 10){ console.log(true); uiProgressBar.style.background = "green"; }else{ console.log(false); uiProgressBar.style.background = "red"; }
CSS
.peg-1-bar{ background-color: grey; border-radius: 50px; height: 20px; width: 400px; margin-left: 30px; } .peg-1-bar-fill{ border-radius: 50px; height: 100%; width: 100%; max-width: 400px; }
HTML
<div class="peg-wrapper"> <div class="peg-name-1"> <h4>1</h4> </div> <div class="peg-1-start-time total-time"> <p class="label-2">Length:</p> <span id="total-time-1">-</span> </div> <div class="peg-1-bar"> <div class="peg-1-bar-fill"> </div> </div> </div>
报错原因
核心问题是uiProgressBar变量为null,也就是DOM查询没找到目标元素,具体原因如下:
- 变量
name未定义,导致选择器变成.undefined-bar-fill,完全匹配不到HTML里的.peg-1-bar-fill - JS代码执行时机过早,DOM还没加载完成就执行了选择器查询,自然找不到元素
- 额外问题:定义了
isActive函数但没有调用,逻辑根本没执行
解决步骤
1. 修复选择器错误
直接使用正确的类名来查询元素,或者先定义name变量:
// 方法一:直接写类名 const uiProgressBar = document.querySelector('.peg-1-bar-fill'); // 方法二:先定义name变量 const name = 'peg-1'; const uiProgressBar = document.querySelector(`.${name}-bar-fill`);
2. 确保DOM加载完成后执行JS
把JS代码放在HTML的</body>标签末尾,或者用DOMContentLoaded事件包裹,确保DOM元素都渲染完成后再查询:
document.addEventListener('DOMContentLoaded', async () => { // 所有JS代码放在这里 });
3. 调用定义好的函数
在合适的位置调用isActive函数,不然逻辑不会执行。
完整修正代码
JavaScript
document.addEventListener('DOMContentLoaded', async () => { const pegsData_url = "https://fakestoreapi.com/products"; const uiProgressBar = document.querySelector('.peg-1-bar-fill'); const pegs1 = document.getElementById("total-time-1"); async function isActive(){ try { const response = await fetch(pegsData_url); // 加请求状态判断,避免接口报错导致后续代码崩溃 if (!response.ok) throw new Error(`请求失败:${response.status}`); const data = await response.json(); console.log(data); // 可选:加数据存在性判断,防止data[1]不存在报错 if(data[1]?.price >= 10){ console.log(true); uiProgressBar.style.background = "green"; }else{ console.log(false); uiProgressBar.style.background = "red"; } } catch (error) { console.error('处理数据时出错:', error); } } // 调用函数执行逻辑 isActive(); });
CSS
.peg-1-bar{ background-color: grey; border-radius: 50px; height: 20px; width: 400px; margin-left: 30px; } .peg-1-bar-fill{ border-radius: 50px; height: 100%; width: 100%; max-width: 400px; }
HTML
<div class="peg-wrapper"> <div class="peg-name-1"> <h4>1</h4> </div> <div class="peg-1-start-time total-time"> <p class="label-2">Length:</p> <span id="total-time-1">-</span> </div> <div class="peg-1-bar"> <div class="peg-1-bar-fill"></div> </div> </div>
内容的提问来源于stack exchange,提问作者Jhona
相关产品推荐
相关产品推荐

