我正在使用JavaScript Fetch从OpenWeather Api获取数据。我有一个表格供用户输入要查看其天气信息的城市。由于某些原因,来自前一个城市的数据仍会在HTML页面中弹出,而不是消失以代替新数据。如何清除内存,以使新搜索城市的新天气信息保留在页面中?以下是JS和HTML的代码
var weatherData = document.getElementById("weather_data");
weatherData.addEventListener('click',function(e){
e.preventDefault();
var cityName = document.getElementById("cityName").value;
var url = "https://api.openweathermap.org/data/2.5/weather?q="+cityName+"&appid=1b81668fc60a1d1905a3e5a311d45414";
if(cityName == ""){
alert("Enter a city name");
}else{
fetch(url).then(function(response){
if(response.ok){
return response.json();
}else{
throw new Error(Error);
}
}).then(function(data){
console.log(data);
const html = `
<h2 class="text-danger text-center"><span class="text-dark">City:</span>${data.name}</h2>
` ;
document.getElementById("display_data").insertAdjacentHTML('afterbegin',html);
}).catch(function(error){
console.log(error);
});
}
});
HTML表格
<form>
<input type="text" id="cityName" placeholder="Enter a city name"><br>
<input type="submit" value="Get Weather Information" id="weather_data">
</form>
Element接口的insertAdjacentHTML()方法将指定的文本解析为HTML或XML,并将结果节点插入到DOM树中的指定位置。它不会重新解析正在使用该元素的元素,因此不会破坏该元素内部的现有元素。这避免了额外的序列化步骤,使其比直接的innerHTML操作快得多。
var weatherData = document.getElementById("weather_data");
weatherData.addEventListener('click',function(e){
e.preventDefault();
var cityName = document.getElementById("cityName").value;
var url = "https://api.openweathermap.org/data/2.5/weather?q="+cityName+"&appid=1b81668fc60a1d1905a3e5a311d45414";
if(cityName == ""){
alert("Enter a city name");
}else{
fetch(url).then(function(response){
if(response.ok){
return response.json();
}else{
throw new Error(Error);
}
}).then(function(data){
const html = `
<h2 class="text-danger text-center"><span class="text-dark">City:</span>${data.name}</h2>
` ;
document.getElementById("display_data").innerHTML = html;
}).catch(function(error){
console.log(error);
});
}
});
<form>
<input type="text" id="cityName" placeholder="Enter a city name"><br>
<input type="submit" value="Get Weather Information" id="weather_data">
</form>
<div id="display_data"></div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句