在 HTML/JavaScript 中显示天气数据时出现问题(displayWeather 错误)

问题描述 投票:0回答:1

let weather = {
  apiKey: "a5fd20552e868ea7597dd68dec1dd543",
  fetchWeather: function(city) {
    fetch("https://api.openweathermap.org/data/2.5/weather?q=" +
        city +
        "&units=metrics&appid=" +
        this.apiKey
      )
      .then((response) => response.json())
      .then(data => displayWeather(data));
  },
  //grabs the data from the api and stores it to a variable for disply sing the corresponding key from the file 
  displayWeather: function(data) {
    const name = data;
    const desc = data.weather[0].description;
    const icon = data.weather[0].icon;
    const temp = data.main.temp;
    const speed = data.wind.speed;
    const humidity = data.main.humidity;
    console.log(name, icon, description, temp, speed, humidity);
    document.querySelector(".city").innerHTML = "Weather in " + name;
    document.querySelector(".icon").src = "https://openweathermap.org/img/wn/" + icon + ".png";
    document.querySelector.innerText = description;




  },
}
body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
  background: #222;
  font-family: sans-serif;
  background-image: url('https://source.unsplash.com/random/?city,night');
  font-size: 120%;
}

.card {
  background: #000000d0;
  color: white;
  padding: 2em;
  border-radius: 2em;
  width: 100%;
  max-width: 420%;
  margin: 1em;
}

.search {
  display: flex;
  align-items: center;
  justify-content: center;
}

button {
  border: none;
  margin: 0.5em;
  border-radius: 50%;
  height: 46px;
  width: 46px;
  background: #7c7c7c2b;
  color: white;
  cursor: pointer;
  transition: 0.2s ease-in-out;
}

input.search-bar {
  border: none;
  outline: none;
  padding: .5em 1em;
  border-radius: 24px;
  background: #7c7c7c2b;
  color: white;
  font-family: inherit;
  font-size: 120%;
}

button:hover {
  background: #7c7c7c6b;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
  background: #222;
  font-family: sans-serif;
  background-image: url('https://source.unsplash.com/random/?city,night');
}

.card {
  background: #000000d0;
  color: white;
  padding: 2em;
  border-radius: 2em;
  width: 100%;
  max-width: 420%;
  margin: 1em;
}

.search {
  display: flex;
  align-items: center;
  justify-content: center;
}

button {
  border: none;
  margin: 0.5em;
  border-radius: 50%;
  height: 46px;
  width: 46px;
  background: #7c7c7c2b;
  color: white;
  cursor: pointer;
  transition: 0.2s ease-in-out;
}

input.search-bar {
  border: none;
  outline: none;
  padding: .5em 1em;
  border-radius: 24px;
  background: #7c7c7c2b;
  color: white;
  font-family: inherit;
  font-size: 120%;
  width: calc(100% - 80px);
}

h1.temp {
  margin: 0;
}

button:hover {
  background: #7c7c7c6b;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Weather App</title>
  <link rel="stylesheet" href="weather.css">
  <script src="./weather.js"></script>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@1,300&display=swap" rel="stylesheet">
</head>

<body>
  <div class="card">
    <div class="search">
      <input type="text" class="search-bar" placeholder="Search">
      <button><svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 1024 1024" height="1.5em" width="1.5em" xmlns="http://www.w3.org/2000/svg"><path d="M909.6 854.5L649.9 594.8C690.2 542.7 712 479 712 412c0-80.2-31.3-155.4-87.9-212.1-56.6-56.7-132-87.9-212.1-87.9s-155.5 31.3-212.1 87.9C143.2 256.5 112 331.8 112 412c0 80.1 31.3 155.5 87.9 212.1C256.5 680.8 331.8 712 412 712c67 0 130.6-21.8 182.7-62l259.7 259.6a8.2 8.2 0 0 0 11.6 0l43.6-43.5a8.2 8.2 0 0 0 0-11.6zM570.4 570.4C528 612.7 471.8 636 412 636s-116-23.3-158.4-65.6C211.3 528 188 471.8 188 412s23.3-116.1 65.6-158.4C296 211.3 352.2 188 412 188s116.1 23.2 158.4 65.6S636 352.2 636 412s-23.3 116.1-65.6 158.4z"></path></svg></button>
    </div>
    <div class="weather">
      <h2 class="city">Denver</h2>
      <h1 class="temp">51° C</h1>
      <img src="" alt="" srcset="" class="icon">
      <div class="description">Cloudy</div>
      <div class="humidity">Humidity: 60%</div>
      <div class="wind">Wind speed: 6.2 km/h</div>

    </div>
  </div>
</body>

</html>

json file

我目前正在使用 HTML 和 JavaScript 开发一个天气应用程序,我从 OpenWeatherMap API 检索天气数据并将其显示在我的 HTML 文档中。但是,我遇到了 displayWeather 函数的问题,该函数负责使用天气信息更新 DOM 元素。我在读取“

weather.description
的数据为‘0’”时遇到错误。

JavaScript 文件的第 15 行代码给了我这个问题。

json file

javascript object
1个回答
0
投票

包含脚本、CSS 和 HTML 的组合 HTML 文档的流程和逻辑,用于根据用户输入(城市名称)获取和显示天气信息,可以是正确的天气信息。

Search Input and Button
:文本输入字段允许用户输入城市名称。旁边有一个按钮,供用户输入城市名称后单击。该按钮有一个 onclick 事件监听器,可以触发 JavaScript 函数来获取天气数据。

Weather Display Area
:此区域设置为在获取天气信息后显示天气信息。它包括城市名称、温度、天气图标、描述、湿度和风速的占位符

JavaScript 部分

fetchWeather
:此方法将城市名称作为输入,使用城市名称和 API 密钥构造请求 URL,并使用 fetch API 向 OpenWeatherMap API 发出 GET 请求。收到响应后,它将响应转换为 JSON 并使用结果数据调用 displayWeather。

displayWeather
:该方法以天气数据JSON为输入,提取相关信息,例如城市名称、天气描述、图标、温度、湿度和风速。然后,它使用该数据更新天气显示区域内的 HTML 元素。

API测试

整个 HTML

另存为

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weather App</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@1,300&display=swap" rel="stylesheet">
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background: #222;
            font-family: sans-serif;
            background-image: url('https://source.unsplash.com/random/?city,night');
            font-size: 120%;
        }

        .card {
            background: #000000d0;
            color: white;
            padding: 2em;
            border-radius: 2em;
            width: 100%;
            max-width: 420px;
            /* Adjusted to px for consistency */
            margin: 1em;
        }

        .search {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        button {
            border: none;
            margin: 0.5em;
            border-radius: 50%;
            height: 46px;
            width: 46px;
            background: #7c7c7c2b;
            color: white;
            cursor: pointer;
            transition: 0.2s ease-in-out;
        }

        input.search-bar {
            border: none;
            outline: none;
            padding: .5em 1em;
            border-radius: 24px;
            background: #7c7c7c2b;
            color: white;
            font-family: inherit;
            font-size: 120%;
            width: calc(100% - 80px);
        }

        button:hover {
            background: #7c7c7c6b;
        }
    </style>
</head>

<body>
    <div class="card">
        <div class="search">
            <input type="text" class="search-bar" placeholder="Enter city name">
            <button onclick="weather.fetchWeather(document.querySelector('.search-bar').value)">
                <svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 1024 1024" height="1.5em"
                    width="1.5em" xmlns="http://www.w3.org/2000/svg">
                    <path
                        d="M909.6 854.5L649.9 594.8C690.2 542.7 712 479 712 412c0-80.2-31.3-155.4-87.9-212.1-56.6-56.7-132-87.9-212.1-87.9s-155.5 31.3-212.1 87.9C143.2 256.5 112 331.8 112 412c0 80.1 31.3 155.5 87.9 212.1C256.5 680.8 331.8 712 412 712c67 0 130.6-21.8 182.7-62l259.7 259.6a8.2 8.2 0 0 0 11.6 0l43.6-43.5a8.2 8.2 0 0 0 0-11.6zM570.4 570.4C528 612.7 471.8 636 412 636s-116-23.3-158.4-65.6C211.3 528 188 471.8 188 412s23.3-116.1 65.6-158.4C296 211.3 352.2 188 412 188s116.1 23.2 158.4 65.6S636 352.2 636 412s-23.3 116.1-65.6 158.4z">
                    </path>
                </svg>
            </button>
        </div>
        <div class="weather">
            <h2 class="city">Weather in <span id="weather-city">...</span></h2>
            <h1 class="temp">...</h1>
            <img src="" alt="" class="icon">
            <div class="description">...</div>
            <div class="humidity">Humidity: ...</div>
            <div class="wind">Wind speed: ...</div>
        </div>
    </div>

    <script>
        let weather = {
            apiKey: "a5fd20552e868ea7597dd68dec1dd543",
            fetchWeather: function (city) {
                fetch("https://api.openweathermap.org/data/2.5/weather?q=" +
                    city +
                    "&units=metric&appid=" + this.apiKey)
                    .then((response) => response.json())
                    .then((data) => this.displayWeather(data));
            },
            displayWeather: function (data) {
                const { name } = data;
                const { description, icon } = data.weather[0];
                const { temp, humidity } = data.main;
                const { speed } = data.wind;

                document.getElementById("weather-city").innerText = `Weather in ${name}`;
                document.querySelector(".icon").src = `https://openweathermap.org/img/wn/${icon}.png`;
                document.querySelector(".description").innerText = `Description: ${description}`; // Ensure description is displayed
                document.querySelector(".temp").innerText = `${temp}° C`;
                document.querySelector(".humidity").innerText = `Humidity: ${humidity}%`;
                document.querySelector(".wind").innerText = `Wind speed: ${speed} km/h`;
            },
        }
    </script>
</body>
</html>

运行 HTML 服务器

VS 代码扩展中的

Live Server

单击右侧/底部的“上线”图标。

访问它

http://127.0.0.1:5500/index.html

结果

© www.soinside.com 2019 - 2024. All rights reserved.