You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript实现不刷新页面清除OpenWeather API历史查询结果?

问题

我用OpenWeather API开发天气查询功能,现在输入新城市时,新数据会叠加在之前的查询结果上。我希望输入另一个城市时自动清除之前的结果,目前做了个刷新按钮靠重载页面清除历史,但想改用JavaScript实现无刷新清除旧结果。

解决方案

核心思路是在每次发起新查询前,清空用于渲染天气数据的DOM容器,避免新元素叠加在旧元素上。具体修改如下:

  1. 在触发查询的handleClick函数开头,清空存放城市名称、天气图标、温度、详情、预报的容器,同时还原详情区域的背景色。
  2. 刷新按钮的逻辑改为无刷新清空,同时清空输入框内容。

修改后的完整代码:

JavaScript 代码

function fetchWeather(city){
    //displayLoading();
    const fetchAPI = fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${api}&units=metric`);

    fetchAPI.then(response => {
        return response.json();
    }).then(data => {
        //hideLoading();
        displayWeather(data)
    })
    .catch(err => {
        error.style.display = "block";
        console.log(err);
    })
}

//Fetch daily and hourly forecast
function fetchForecast(city) {
    const url = `https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${api}&units=metric&cnt=25`;
    fetch(url).then(response => {
        return response.json();
    }).then(data => displayForecast(data))
    .catch(err => {
        console.log(err);
    })
}

//Display animated weather icon
function displayWeatherIcon(weather){
    const icon = document.createElement("img");
    switch(weather){
        case "clear sky":
            icon.setAttribute("src", "./images/clear-day.svg");
            break;
        case "few clouds":
            icon.setAttribute("src", "./images/partly-cloudy-day.svg");
            break;
        case "scattered clouds":
            icon.setAttribute("src", "./images/cloudy.svg");
            break;
        case "overcast clouds":
        case "broken clouds":
            icon.setAttribute("src", "./images/overcast.svg");
            break;
        case "shower rain":
            icon.setAttribute("src", "./images/overcast-rain.svg");
            break;
        case "light rain":
        case "moderate rain":
        case "rain":
            icon.setAttribute("src", "./images/overcast-day-drizzle.svg");
            break;
        case "thunderstorm":
            icon.setAttribute("src", "./images/thunderstorm-overcast.svg");
            break;
        case "snow":
            icon.setAttribute("src", "./images/snow.svg");
            break;
        case "mist":
            icon.setAttribute("src", "./images/mist.svg");
            break;
    }
    row.prepend(icon);
}

//Display weather informations from fetched api
function displayWeather(weather){
    const city = document.createElement("h1");
    city.innerHTML = `${weather.name}, ${weather.sys.country}`;
    header.prepend(city);

    const weatherDesc = weather.weather[0].description;
    displayWeatherIcon(weatherDesc);

    const temp = document.createElement("p");
    const temperature = weather.main.temp;
    temp.innerHTML = `${temperature.toFixed()}°C`;
    row.append(temp);

    info.style.backgroundColor = "#F0F0F0";

    const desc = document.createElement("p");
    desc.innerHTML = weather.weather[0].description;
    info.append(desc);
    const cloudIcon = document.createElement("i");
    cloudIcon.setAttribute("class","fas fa-cloud-sun-rain");
    desc.prepend(cloudIcon);

    const humidity = document.createElement("p");
    humidity.innerHTML = `Humidity: ${weather.main.humidity}%`;
    info.append(humidity);
    const humidIcon = document.createElement("i");
    humidIcon.setAttribute("class","fas fa-water");
    humidity.prepend(humidIcon);

    const wind = document.createElement("p");
    wind.innerHTML = `Wind: ${weather.wind.speed} m/s`;
    info.append(wind);
    const windIcon = document.createElement("i");
    windIcon.setAttribute("class","fas fa-wind");
    wind.prepend(windIcon);
}

//Display daily forecast informations from fetched api
function displayForecast(forecast){
    const list = forecast.list;
    for(let index = 7; index < list.length; index+=8){
        const col_one = document.createElement("div");
        const col_one_time = document.createElement("div");
        let dateString = list[index].dt_txt;
        let date = new Date(dateString).toLocaleDateString('en-us', {weekday:'long'})
        let time = new Date(dateString).toLocaleTimeString('en-us', {hour: '2-digit', minute: '2-digit'})
        col_one.setAttribute("class", `column-${index}`);
        col_one.innerHTML = date;
        col_one_time.innerHTML = time;
        middle.append(col_one);
        col_one.append(col_one_time);

        let col_one_icon = document.createElement("img");
        col_one_icon.setAttribute("src", "http://openweathermap.org/img/w/" + list[index].weather[0].icon + ".png");
        col_one.append(col_one_icon);

        let col_one_temp = document.createElement("div");
        col_one_temp.innerHTML = `${list[index].main.temp.toFixed(0)}°C`;
        col_one.append(col_one_temp);
    }
}

function handleClick(event){
    event.preventDefault();
    // 清空之前的所有结果
    header.innerHTML = '';
    row.innerHTML = '';
    info.innerHTML = '';
    middle.innerHTML = '';
    info.style.backgroundColor = 'transparent'; // 还原背景色
    const cityInput = document.getElementById("cityInput").value;
    fetchWeather(cityInput);
    fetchForecast(cityInput);
}

function refreshPage(){
    // 无刷新清空所有内容
    header.innerHTML = '';
    row.innerHTML = '';
    info.innerHTML = '';
    middle.innerHTML = '';
    info.style.backgroundColor = 'transparent';
    document.getElementById("cityInput").value = ''; // 清空输入框
}

const button = document.querySelector('#enter');
button.addEventListener('click', handleClick);

const refresh = document.querySelector('#refresh');
refresh.addEventListener('click', refreshPage);

HTML 代码

<div>
    <input id="cityInput">
    <button id="enter" >Enter</button>
    <button id="refresh">Refresh</button>
</div>

内容的提问来源于stack exchange,提问作者josh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 18:27:02