天气预报30天查询 (天气预报30天查询软件)

长沙桑拿 07-29 阅读:2 评论:4

输入您的城市或邮政编码:

天气预报30天查询 (天气预报30天查询软件)
javascript // weather.jsconst API_KEY = "YOUR_API_KEY";const getWeather = (location) => {const url = `${location}&appid=${API_KEY}&units=metric`;return fetch(url).then((response) => response.json()).catch((error) => {console.error("Error:", error);alert("获取天气数据失败。请重试。");}); };const displayResults = (data) => {const resultsDiv = document.getElementById("results");// 清除现有结果resultsDiv.innerHTML = "";const city = data.city.name;const country = data.city.country;// 创建标题const title = document.createElement("h2");title.textContent = `天气预报:${city}, ${country}`;resultsDiv.appendChild(title);// 创建表格const table = document.createElement("table");table.classList.add("weather-table");resultsDiv.appendChild(table);// 表头const tableHeaders = ["日期", "天气", "最低气温", "最高气温"];const headerRow = document.createElement("tr");tableHeaders.forEach((header) => {const th = document.createElement("th");th.textContent = header;headerRow.appendChild(th);});table.appendChild(headerRow);// 表格数据const forecast = data.list;forecast.forEach((day) => {// 获取日期const date = new Date(day.dt 1000).toLocaleDateString();// 获取天气图标const weatherIcon = day.weather[0].icon;const iconUrl = `${weatherIcon}@2x.png`;// 创建表格行const row = document.createElement("tr");// 日期const dateCell = document.createElement("td");dateCell.textContent = date;row.appendChild(dateCell);// 天气const weatherCell = document.createElement("td");const weatherDescription = day.weather[0].description;weatherCell.innerHTML = ` ${weatherDescription}`;row.appendChild(weatherCell);// 最低气温const minTempCell = document.createElement("td");minTempCell.textContent = `${Math.round(day.main.temp_min)} °C`; row.appendChild(minTempCell);// 最高气温const maxTempCell = document.createElement("td");maxTempCell.textContent = `${Math.round(day.main.temp_max)} °C`;row.appendChild(maxTempCell);// 将行添加到表格table.appendChild(row);}); };const submitForm = (e) => {e.preventDefault();const location = e.target.querySelector("input[name=location]").value;getWeather(location).then((data) => displayResults(data)).catch((error) => console.error("Error:", error)); };const form = document.querySelector("form"); form.addEventListener("submit", submitForm);
版权声明

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