You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发天气APP调用OpenWeatherMap API设置图标时DOM报错求助

天气APP动态加载OpenWeatherMap图标报错解决

你的两个报错本质都是**document.querySelector("#weatherIcon")返回了null**,也就是JS找不到对应的DOM元素,同时代码里还有一处语法错误,以下是具体排查和解决步骤:

一、核心问题:DOM元素未找到

出现Cannot read properties of null的原因只有一个:当前页面中不存在id="weatherIcon"的元素,或者代码执行时该元素还没加载。

排查方向:

  1. 检查HTML元素

    • 确认HTML里有且仅有一个<img>元素的id是weatherIcon,注意ID是大小写敏感的,别写成weathericon或其他拼写错误。
    • 示例正确的HTML结构:
      <img id="weatherIcon" alt="天气图标">
      
  2. 调整JS执行时机

    • 如果你的JS代码放在<head>标签里,或者DOM元素之前,会导致代码执行时元素还没渲染,querySelector自然找不到。
    • 解决办法:
      • 把JS代码移到HTML文档的</body>结束标签之前;
      • 或者用DOMContentLoaded事件包裹代码,确保DOM加载完成后再执行:
        document.addEventListener('DOMContentLoaded', function() {
          // 这里放你的weatherData对象以及调用代码
        });
        

二、代码中的语法错误

你第一种写法里的setAttribute参数有误:"src,"多了个逗号,正确写法应该是:

document.querySelector("#weatherIcon").setAttribute("src", `https://openweathermap.org/img/wn/${icon}.png`);

三、修正后的代码示例

weatherData = {
    getWeatherInfo: function (city) {
        fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=imperial&appid=${apiTag}`)
        .then((response) => response.json())
        .then((data) => this.unveilWeather(data));
    },
    unveilWeather: function (data) {
        const {name} = data;
        const {icon, description} = data.weather[0];
        const {temp, humidity} = data.main;
        const {speed} = data.wind;
        console.log(name, icon, description, temp, humidity, speed);
        
        // 先判断元素是否存在再操作,避免报错
        const weatherIconEl = document.querySelector("#weatherIcon");
        if (weatherIconEl) {
            weatherIconEl.src = `https://openweathermap.org/img/wn/${icon}.png`;
        } else {
            console.error("未找到id为weatherIcon的图片元素");
        }

        document.querySelector("#City").innerText = "Weather in " + name; 
        document.querySelector("#cityWeatherDescription").innerText = description;
        document.querySelector(".temperature").innerText = Math.round(temp) + " °F";
        document.querySelector(".humidity-weather-stat").innerText = "Humidity :" +  humidity + "%";
        document.querySelector(".wind-speed-weather-stat").innerText = "Wind Speed :" + speed + "m/hr";
    },
};

内容的提问来源于stack exchange,提问作者user19846413

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 22:20:29