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

清空历史数据后仅显示5天预报最后一天数据的问题求助

问题解决:5天天气预报仅显示最后一天的原因及修复方案

兄弟,你这问题的根源一眼就能看出来——你把清空容器的$('#fiveDay').empty()写在循环体内部了!

每次循环到符合18:00:00条件的预报数据时,你先把#fiveDay里的内容清空,再添加当天的预报。这么一来,前4天的内容刚加上就被下一次循环的清空操作删掉了,最后自然就只剩最后一天的数据咯。

修复后的代码

$.ajax({ 
    url: queryURLThree, 
    method: "GET" 
}).then(function (forecastResT) { 
    // 把清空操作移到循环外面,只清空一次旧数据
    $('#fiveDay').empty();
    for (var i = 0; i < forecastResT.list.length; i++) { 
        if (forecastResT.list[i].dt_txt.indexOf("18:00:00") !== -1) { 
            var day = forecastResT.list[i].dt_txt.split(" ") 
            var forecastNameS = $('<div class="col"><p>' + day[0] + '</p>') 
            // 根据天气状况添加图标
            var imgOne = $("<img>").attr("src", "http://openweathermap.org/img/w/" + forecastResT.list[i].weather[0].icon + ".png"); 
            var tempFiveOne = $('<div id = "tempFive">'+ 'Temperature: ' +forecastResT.list[i].main.temp + '<div>'); 
            var humFiveOne = $('<div id = "humFive"> '+'Humidity: ' + forecastResT.list[i].main.humidity + '<div>'); 
            
            forecastNameS.append(imgOne); 
            forecastNameS.append(tempFiveOne); 
            forecastNameS.append(humFiveOne); 
            $('#fiveDay').append(forecastNameS); 
        } 
    } 
});

关键修改说明

  • 将$('#fiveDay').empty()从循环内部移到for循环之前,确保只在渲染新预报前清空一次旧内容,避免中途删除已添加的预报。
  • 循环内只负责创建单日预报元素并追加到容器中,不再重复执行清空操作。

这样修改后,5天的预报内容就会依次添加到容器里,不会被中途清空啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:28:56