【问题标题】:Uncaught (in promise) TypeError: Cannot set properties of null (setting 'innerText') in OpenWetherMap APIUncaught (in promise) TypeError: Cannot set properties of null (setting 'innerText') in OpenWetherMap API
【发布时间】:2022-01-19 12:14:02
【问题描述】:
function getResults(query) {
            fetch(`${api.base}weather?q=${query}&units=metric&appid=${api.key}`)
                .then(weather => {
                    return weather.json();
                }).then(displayResults);
        }
        function displayResults(weather) {
            let city = document.querySelector('.location .city');
            city.innerText = `${weather.name}, ${weather.sys.country}`;

            let now = new Date();
            let date = document.querySelector('.location .date');
            date.innerText = dateBuilder(now);

            let temp = document.querySelector('.current .temptater');
            temp.innerHTML = `${Math.round(weather.main.temp)}<span>°c</span>`;

            let weatherType = document.querySelector('.current .weather');
            weatherType.innerText = weather.weather[0].main;

            let hilow = document.querySelector('.hi-low');
            hilow.innerText = `${Math.round(weather.main.temp_min)}°c / ${Math.round(weather.main.temp_max)}°c`;
        }

当我访问数组中的嵌套对象时,会显示

Uncaught (in promise) TypeError: Cannot set properties of null (setting 'innerText')

这只发生在

let weatherType = document.querySelector('.current .weather');
            weatherType.innerText = weather.weather[0].main;

这是一个API调用的JSON文件

{
  "coord": {
    "lon": -0.1257,
    "lat": 51.5085
  },
  "weather": [
    {
      "id": 804,
      "main": "Clouds",
      "description": "overcast clouds",
      "icon": "04d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 10.96,
    "feels_like": 10.2,
    "temp_min": 9.65,
    "temp_max": 11.98,
    "pressure": 1039,
    "humidity": 80
  },
  "visibility": 10000,
  "wind": {
    "speed": 1.54,
    "deg": 340
  },
  "clouds": {
    "all": 90
  },
  "dt": 1639651705,
  "sys": {
    "type": 2,
    "id": 2019646,
    "country": "GB",
    "sunrise": 1639641643,
    "sunset": 1639669905
  },
  "timezone": 0,
  "id": 2643743,
  "name": "London",
  "cod": 200
}

其他一切都运行良好,但我不知道为什么会这样。 有什么解决办法吗?

【问题讨论】:

  • 请分享您网页的 HTML - 如下所示,您的 .current 元素中可能没有 &lt;div class="weather"&gt;

标签: javascript json api


【解决方案1】:

document.querySelector 将在没有返回匹配元素时返回 null.current .weather 很可能没有引用您的 HTML 中的任何内容。

【讨论】:

    猜你喜欢
    • 2021-12-21
    • 2021-12-12
    • 1970-01-01
    • 2022-07-01
    • 2022-01-11
    • 2022-01-11
    • 1970-01-01
    • 2022-10-09
    • 2022-07-21
    相关资源
    最近更新 更多