实时快报 (实时快报气温快报)

深圳休闲 05-07 阅读:11 评论:0
实时快报 (实时快报气温快报)

气温快报

当前天气

未来天气预报

javascript // 定义 API 密钥和天气 API URL const API_KEY = 'YOUR_API_KEY'; const WEATHER_API_URL = 'https://api.openweathermap.org/data/2.5/weather'; const FORECAST_API_URL = 'https://api.openweathermap.org/data/2.5/forecast';// 获取天气数据 async function getWeatherData(city) {const response = await fetch(`${WEATHER_API_URL}?q=${city}&appid=${API_KEY}`);return await response.json(); }// 获取天气预报数据 async function getForecastData(city) {const response = await fetch(`${FORECAST_API_URL}?q=${city}&appid=${API_KEY}`);return await response.json(); }// 显示当前天气 function displayCurrentWeather(data) {const temperature = Math.round(data.main.temp - 273.15);const conditions = data.weather[0].main;document.getElementById('weather-temperature').innerHTML = `${temperature}°C`;document.getElementById('weather-conditions').innerHTML = conditions; }// 显示未来天气预报 function displayForecast(data) {const forecastList= document.getElementById('weather-forecast-list');data.list.forEach((forecast) => {const date = new Date(forecast.dt 1000);const temperature = Math.round(forecast.main.temp - 273.15);const conditions = forecast.weather[0].main;const forecastItem = document.createElement('li');forecastItem.innerHTML = `
${date.toLocaleDateString()}
${temperature}°C
${conditions}
`;forecastList.appendChild(forecastItem);}); }// 获取并显示天气数据 function init() {const city = prompt('请输入城市名称:');getWeatherData(city).then((data) => displayCurrentWeather(data));getForecastData(city).then((data) => displayForecast(data)); }init();
版权声明

本文仅代表作者观点,不代表深圳桑拿立场。
本文系作者授权发表,未经许可,不得转载。

分享:

扫一扫在手机阅读、分享本文

文章排行