You need to enable JavaScript to run this app. 基于HTML+JS的动态天气搜索:输入城市后无刷新无法更新数据
优惠活动
大模型
产品
解决方案
定价
更多

基于HTML+JS的动态天气搜索:输入城市后无刷新无法更新数据

核心问题定位
  • 条件判断仅在页面首次加载时执行一次:原脚本在最外层读取一次输入框的值做分支判断,后续不管用户输入新内容、点击按钮,这段逻辑都不会重新运行,无法触发新的查询流程。
  • 事件绑定逻辑错位:原代码将按钮的点击监听写在getLocation函数内部,只有页面初始加载时走“输入框为空”的分支,才会给按钮绑定事件;如果输入框初始就有值,直接走searchParams分支时,按钮根本没有绑定任何点击行为,点击无响应。
  • 缺少统一的查询触发入口:地理定位、城市查询两个逻辑完全独立,没有公共的调度层,无法在不刷新页面的情况下复用逻辑完成状态切换。
可运行的修正代码

把逻辑做分层重构,拆分公共能力和业务分支,实现无刷新的动态查询:

// 初始化全局DOM引用,避免重复查询DOM树
const locationTipEl = document.getElementById('myLocation')
const tempDisplayEl = document.getElementById('windSpeed')
const cityInputEl = document.getElementById('cidade')
const submitBtnEl = document.getElementById('botao')
const OPENWEATHER_API_KEY = '03838cfa6af6494abe9a10e2f9d3ef17'

// 通用渲染函数:统一处理接口返回的渲染逻辑
function renderWeatherResult(res) {
  if (res.cod !== 200) {
    tempDisplayEl.textContent = `查询失败:${res.message}`
    return
  }
  tempDisplayEl.innerHTML = `实时温度:${res.main.temp} ℃`
}

// 分支1:通过地理定位获取天气
function fetchWeatherByGeo() {
  if (!navigator.geolocation) {
    locationTipEl.textContent = '当前浏览器不支持地理定位能力'
    return
  }
  // 发起定位请求
  navigator.geolocation.getCurrentPosition((position) => {
    const { latitude, longitude } = position.coords
    locationTipEl.innerHTML = `当前定位:纬度 ${latitude.toFixed(2)},经度 ${longitude.toFixed(2)}`
    // 拼接接口地址
    const apiUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${OPENWEATHER_API_KEY}&units=metric&lang=zh_cn`
    fetch(apiUrl)
      .then(res => res.json())
      .then(renderWeatherResult)
      .catch(err => tempDisplayEl.textContent = `接口请求异常:${err.message}`)
  })
}

// 分支2:通过城市名获取天气
function fetchWeatherByCity(cityName) {
  const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${OPENWEATHER_API_KEY}&units=metric&lang=zh_cn`
  fetch(apiUrl)
    .then(res => res.json())
    .then(renderWeatherResult)
    .catch(err => tempDisplayEl.textContent = `接口请求异常:${err.message}`)
}

// 统一调度入口:每次触发查询时,实时读取输入框状态,分发到对应分支
function handleQueryTrigger() {
  // 清空上一次的提示和结果,避免新旧数据混排
  locationTipEl.textContent = ''
  tempDisplayEl.textContent = '正在查询...'
  // 实时读取输入框值,去掉首尾空格
  const inputCityVal = cityInputEl.value.trim()
  // 根据输入状态走对应分支
  if (!inputCityVal) {
    fetchWeatherByGeo()
  } else {
    fetchWeatherByCity(inputCityVal)
  }
}

// 全局绑定交互事件,和业务分支解耦
// 按钮点击触发查询
submitBtnEl.addEventListener('click', handleQueryTrigger)
// 输入框按回车也能触发查询,优化体验
cityInputEl.addEventListener('keydown', (e) => {
  if (e.key === 'Enter') handleQueryTrigger()
})
// 页面首次加载完成时,自动跑一次初始查询
window.addEventListener('DOMContentLoaded', handleQueryTrigger)
落地注意点
  • 取值时务必做trim()处理,避免用户输入全空格的场景被判定为有效输入,发起无效请求。
  • 原HTML中存在无匹配的闭合</div>标签,建议删除,避免浏览器DOM解析异常。
  • 可以额外增加请求取消逻辑,避免用户连续点击按钮时,多个接口请求返回乱序导致页面显示错误结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.01 16:24:05