【发布时间】:2021-05-11 12:14:06
【问题描述】:
我正在创建一个每 5 秒更新一次的天气仪表板。我希望用户能够更改目标城市,并使用新数据更新仪表板。 问题是每次他们输入一个新城市时,以前的数据都会保留下来,并且似乎在循环用户迄今为止所做的所有输入。
我希望在用户输入新城市后更新数据,而不是添加。这是我的代码:
window.onload = function() {
const api_key = "c7eedc2fa8594d69aa6122025212904";
const inputCity = document.getElementById("inputCity");
const getCity = document.querySelector("form");
getCity.addEventListener("submit", e => {
// Prevent the form from submission
e.preventDefault();
var inputVal = inputCity.value;
var api_url = "http://api.weatherapi.com/v1/forecast.json?key=" + api_key + "&q=" + inputVal + "&days=3&aqi=no&alerts=no";
// Get the dataset
function refreshData() {
fetch(api_url).then(response => {
response.json().then(json => {
var dataset = json;
var output = formatResponse(dataset);
})
// Catch error - for example, the user doesn't input a valid city / postcode / country
.catch(error => console.log("not ok")); // TO BE IMPROVED
})
}
refreshData(); // Display the dashboard immediately
setInterval(refreshData, 5000); // And then refresh the dashboard every X milliseconds
});
function formatResponse(dataset) {
console.log(dataset);
// Current temp
var currentTemp = [dataset.current.temp_c];
console.log(currentTemp);
document.getElementById("currentTempDsp").innerHTML = currentTemp + "°";
// Current state icon
var currentIcon = [dataset.current.condition.icon];
console.log(currentIcon);
document.getElementById("iconDsp").src = "http://" + currentIcon;
// Current state text
var currentText = [dataset.current.condition.text];
console.log(currentText[0]);
document.getElementById("currentStateDsp").innerHTML = currentText;
}
}
<form id="getCity" class="search">
<label id="labelCity">Search for a city...</label></br>
<input type="text" id="inputCity" class="inputCity" placeholder="Type city name here...">
<button id="submitCity" type="submit" class="submitCity"><i class="fas fa-search"></i>Submit</button>
</form>
<div class="state">
<h2 id="currentTempDsp"></h2>
<img id="iconDsp"/>
<span id="currentStateDsp"></span>
</div>
</div>
</div>
【问题讨论】:
-
您必须在变量中存储对当前间隔的引用,然后在设置新间隔之前使用
clearInterval()清除。 -
@esqew 谢谢,我试过这样做,但不幸的是它不起作用:(
-
您能否更具体地说明为什么链接副本中的答案不符合您的要求(错误消息、预期与实际行为)?
-
@esqew 它没有改变任何东西,因为我遇到了同样的问题。我将设置的间隔存储在一个变量(间隔)中并添加了 clearInterval(interval);在提交事件侦听器中到处都是,但什么都没有。您能否提供一些代码说明您将如何做到这一点?
标签: javascript json user-input json-query