javascript - 如何获取用户输入与 API 交互
问题描述
我试图让用户在搜索栏中输入一个城市,然后单击搜索以显示用户城市的信息。目前我对城市进行了硬编码,但想让它成为用户的选择。
CodePen 链接 = https://codepen.io/joshdbushnell/pen/MNegpy
HTML
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div id = "containAll">
<input id = "searchBar" placeholder = "Search for location"></input>
<button id = "submit">Search</button>
<div class = "weather-container">
<img class = "icon">
<p class = "weather"></p>
<p class = "temp"></p>
</div>
</div>
</body>
</html>
Javascript
var url = "https://api.openweathermap.org/data/2.5/weather?q="
var city = "Orlando"
var units = "&units=imperial"
var key = "&&apikey=c6c565397f8f456020e7b3fe71fa3ff5"
$.getJSON(
url + city + units + key,
function(data){
//console.log(data);
var icon = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
var temp = Math.floor(data.main.temp);
var weather = data.weather[0].main;
$(".icon").attr("src", icon);
$(".weather").append(weather);
$(".temp").append(temp).append('°');
}
);
解决方案
您可以通过在单击按钮时使用搜索栏值更新变量来onclick
找到它,从而将函数添加到按钮:id
city
var button = document.getElementById("submit");
button.onclick = function()
{
var city = getElementById("searchBar").value;
}
enter
如果在搜索栏中使用键而不是按钮,您还可以通过执行以下操作添加侦听器:
document.getElementById("searchBar").addEventListener("keydown", function(event)
{
if (event.key === "Enter") //Can also use event.which === 13 or event.keyCode === 13
{
event.preventDefault();
var city = getElementById("searchBar").value;
}
});
注意:这只是为了更新您的变量,city
我没有使用它来执行任何其他操作。这也是在没有任何框架的纯 JS 中。
推荐阅读
- android - app-debug.apk 是应用程序的实际大小吗?
- java - 垃圾收集是自动工作还是手动工作?
- python - Pytorch:变量数据必须是张量,但有变量
- android - 如何获得 onClick 状态?
- c - 使用带有函数的二维字符数组
- javascript - 数组或迭代器中的每个孩子都应该有一个唯一的“key”道具。在反应js?
- vim - Vim 插入模式下的所有移动和编辑都是不好的做法吗?
- html - Ruby Table CSS - 背景无法正常工作
- angular - 将模板导入 Angular 6 的方法
- jquery - 使用简单 Jquery 的多个模态相同页面(在桌面和移动设备上响应)