javascript
// 加载天气预报数据
async function fetchWeatherData() {const response = await fetch("https://api.openweathermap.org/data/2.5/onecall?lat=30.67&lon=104.06&exclude=minutely,hourly&units=metric&appid=[YOUR_API_KEY]");return response.json();
}// 更新当前天气信息
function updateCurrentWeather(data) {const currentWeatherData = data.current;document.getElementById("current-temperature").textContent = Math.round(currentWeatherData.temp);document.getElementById("current-description").textContent =currentWeatherData.weather[0].description;document.getElementById("current-wind").textContent = Math.round(currentWeatherData.wind_speed);document.getElementById("current-humidity").textContent =Math.round(currentWeatherData.humidity);
}// 更新一周天气预报
function updateWeeklyForecast(data) {const dailyForecastData = data.daily;const weeklyForecastList = document.getElementById("weekly-forecast-list");dailyForecastData.forEach((dayData) => {const date = new Date(dayData.dt 1000);const day = date.toLocaleDateString();const tempMax = Math.round(dayData.temp.max);const tempMin = Math.round(dayData.temp.min);const description = dayData.weather[0].description;const listItem = document.createElement("li");listItem.classList.add("weekly-forecast-item");const dateElement = document.createElement("p");dateElement.textContent = day;const tempElement = document.createElement("p");tempElement.textContent = `${tempMin}°C - ${tempMax}°C`;const descriptionElement = document.createElement("p");descriptionElement.textContent = description;listItem.appendChild(dateElement);listItem.appendChild(tempElement);listItem.appendChild(descriptionElement);weeklyForecastList.appendChild(listItem);});
}// 页面加载后立即加载数据并更新天气信息
window.addEventListener("load", async () => {const data = await fetchWeatherData();updateCurrentWeather(data);updateWeeklyForecast(data);
});