使用用户输入更改Javascript变量的值

时间:2017-06-30 11:11:48

标签: javascript html

我目前正在天气网站上工作。我想将用户输入到变量当前城市的变量中。希望有人帮助我。

<article>
  <input id="user_Input" type="text" placeholder="Ortsuchen...">
  <button id="submit" onclick="changeValue()">Submit</button>
  <span id="location">Unknown</span>
</article>
<section>
      <div>
          <div><span id="day0" class="ml:.25r fs:6r">0</span></div>
          <div><span id="wochentage">0</span></div>
      </div>
      <div>
          <img id="icon0">
      </div>
      <div>
          <span id="wind">0</span><span id="direction"></span><span></span>
      </div>
      <div>
          <span id="humidity">0</span><span>%</span>
      </div>
</section>
var result = $("<div/>").html("&#8216;Title text in quotes &#8217;: Dash: &#8211; ").text();

点击提交按钮后,

位置正在更新。但变量的值不会改变。我已经查看了stackoverflow和其他网站,但没有找到任何适用于我的解决方案。

1 个答案:

答案 0 :(得分:1)

第一名:您的请求只能在page load上运行。你需要在用户更改userInput之后再次运行它。所以将它作为一个函数并在每次userInput更改时调用它。

var userInput = "London";

function changeValue() {
  userInput = document.getElementById("user_Input").value;
  document.getElementById("location").innerHTML = document.getElementById("user_Input").value;
  
  ajax_call();
}

function ajax_call(){

var api = "http://api.openweathermap.org/data/2.5/forecast/daily?q=";
var units = "&units=metric";
var url2 = api + userInput + units + APPID;

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if(this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        
        var iconCode = myObj.list[0].weather[0].id;
        var directions = myObj.list[0].deg;

        for (var i = 0; i < 7; i++) {
            
            document.getElementById("day" + i).innerHTML =  Math.round(myObj.list[i].temp.day) + "°";
            document.getElementById("icon" + i).src = "sl_line/" + iconCode + ".svg";
            document.getElementById("wota" + i).innerHTML = wochentag[day.getDay()+i+1];
            document.getElementById("humidity").innerHTML = Math.round(myObj.list[0].humidity);
            document.getElementById("wind").innerHTML = myObj.list[0].speed + " m/s";
            document.getElementById("direction").innerHTML = directions;
        }
    }
};

xmlhttp.open("GET", url2, true);
xmlhttp.send();

}

window.onload = function() {

    ajax_call();
};
<article>
  <input id="user_Input" type="text" placeholder="Ortsuchen...">
  <button id="submit" onclick="changeValue()">Submit</button>
  <span id="location">Unknown</span>
</article>
<section>
      <div>
          <div><span id="day0" class="ml:.25r fs:6r">0</span></div>
          <div><span id="wochentage">0</span></div>
      </div>
      <div>
          <img id="icon0">
      </div>
      <div>
          <span id="wind">0</span><span id="direction"></span><span></span>
      </div>
      <div>
          <span id="humidity">0</span><span>%</span>
      </div>
</section>