首页 > 解决方案 > 如何获取用户输入与 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('°');
  }
);

标签: javascripthtmlapi

解决方案


您可以通过在单击按钮时使用搜索栏值更新变量来onclick找到它,从而将函数添加到按钮:idcity

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 中。


推荐阅读