gpt4 book ai didi

javascript - document.getElementById (' ' ).value 返回未定义

转载 作者:行者123 更新时间:2023-12-04 08:50:46 27 4
gpt4 key购买 nike

我正在为天气应用程序使用 API。但是当涉及到使用 <input type="text"> 创建搜索栏时和一个 document.getElementById(' ').value它返回我未定义(当我注销时)。所以我想知道是否有任何其他方式来获取输入。
HTML:

<form class="search">

<input type="text" id="Search" name="Search" placeholder="Search city..." style="width: 50%; padding: 10px;">

<button type="submit" id="button" style="padding: 10px;">SEARCH</button>

</form>
JavaScript:
let location1 = document.getElementById('Search').value;
let api1 = 'http://api.openweathermap.org/data/2.5/weather?q=';
let api2 = '&appid=ece23eaa3a8d940b327a0cdc41c1e344&units=metric';

let API = api1 + location1 + api2;

// MAIN WEATHER */
fetch(API) // Current weather API
任何帮助将不胜感激

最佳答案

问题是我设置了一个按钮,该按钮的功能是重新加载页面。我的教授告诉我的解决方案是将整个 JS 代码设置为一个函数。当按下按钮时激活该功能。我在这里留下工作代码:
HTML

<form class="search">

<input type="text" id="Search" name="Search" placeholder="Search city..." style="width: 50%; padding: 10px;">
<button type="button" id="button" style="padding: 10px;" onclick="find_weather()" >SEARCH</button>

</form>
JS
let find_weather= function(){
let location1 = document.getElementById('Search').value;
let api1 = 'http://api.openweathermap.org/data/2.5/weather?q=';
let api2 = '&appid=ece23eaa3a8d940b327a0cdc41c1e344&units=metric';

let api3 = 'http://api.openweathermap.org/data/2.5/forecast?q=';
let api4 = '&appid=ece23eaa3a8d940b327a0cdc41c1e344&units=Metric';

let API = api1 + location1 + api2;
let API2 = api3 + location1 + api4;


fetch(API).then(response => response.json())
...
感谢所有帮助过我的人 <3

关于javascript - document.getElementById (' ' ).value 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64107979/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com