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

如何使JS函数获取HTML表单用户输入值?天气APP开发问题

解决天气应用表单提交获取用户输入的问题

问题说明

作为JS和HTML新手,我正在用OpenWeatherMap API开发基础天气应用,目前能手动指定城市调用getWeatherByLocation函数获取并展示数据,但想实现用户通过表单输入城市后自动加载对应天气信息。已添加表单submit事件监听,但不清楚如何把用户输入值传递给函数。

原代码问题点

  1. 表单提交事件中,错误地将按钮元素赋值给location,而非获取输入框的内容
  2. 未处理API调用失败的情况(比如城市不存在)

修正后的代码

HTML代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width,initial-scale=1.0"/>
        <title>My First Weather App</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css">
    </head>
    <body>
        <h1>My First Weather App</h1>
        <form class="userFormInput" id="form">
            <label for="location" id="formUserLocation">Location</label><br>
            <input type="text" placeholder="Search By Location" id="formUserTextInput" name="Location"><br>
            <button type="submit" id="search">Search</button>
        </form>
        <h2>Current Weather in </h2>
        <p >City: <span id="currentResultCity"></span></p>
        <div class="displayCurrentWeatherSection">
            
            <p >Temperature: <span id="currentTemperatureResult"></span></p>
            <p >Weather: <span id="currentWeatherResult"></span></p>
            <p >Humidity: <span id="currentHumidityResult"></span></p>
            <p >Wind Speed: <span id="currentWindResult"></span></p>
        </div>
    <main>

    </main>
    <script src="./assets/js/script.js"></script> 
    </body>

    <footer>©2023 - Created by - Ollie Lloyd</footer>
</html>

修正后的JavaScript代码

const apiKey = "74190a20c1ddbdc4f115b7fc58fd24ac";
const APIURL = `https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid=${apiKey}`;
const APIURLForecast = `https://api.openweathermap.org/data/2.5/forecast?lat={lat}&lon={lon}&appid=${apiKey}`;
const form = document.getElementById('form');
const searchInput = document.getElementById('formUserTextInput');

const urlApiCall = (location) =>
    `https://api.openweathermap.org/data/2.5/weather?q=${location}&appid=${apiKey}&units=imperial`;

function getWeatherByLocation(location){
    fetch(urlApiCall(location))
    .then(function (response){
        if (!response.ok) {
            throw new Error('城市未找到或API请求失败');
        }
        return response.json();
    })
    .then(function(data){
        document.getElementById("currentResultCity").innerHTML = data.name;    
        document.getElementById("currentTemperatureResult").innerHTML = `${data.main.temp} °F`;
        document.getElementById("currentHumidityResult").innerHTML = data.main.humidity;
        document.getElementById("currentWeatherResult").innerHTML = data.weather[0].description;
        document.getElementById("currentWindResult").innerHTML = `${data.wind.speed} mph`;
    })
    .catch(function(error){
        alert(error.message);
    });
    
}

getWeatherByLocation("boston");

form.addEventListener('submit', (e) => {
    e.preventDefault();
    const location = searchInput.value.trim();

    if (location) {
        getWeatherByLocation(location);
        searchInput.value = '';
    } else {
        alert('请输入城市名称');
    }
});

修改说明

  1. 获取正确的输入元素:将原获取按钮的代码改为获取输入框元素formUserTextInput
  2. 获取用户输入值:在表单提交事件中,通过searchInput.value.trim()获取用户输入的城市名称,同时去除首尾空格
  3. 添加错误处理:判断API响应状态,捕获请求失败的情况并提示用户
  4. 优化用户体验:提交成功后清空输入框,输入为空时给出提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 23:18:33