问题描述
我正在从天气api信息中获取我的应用程序。我设法在我的html中引入和更改“ location-timezone”,“ temperature-degree”和“ tempemperature-description”的信息;但我无法将mi“ temperature-icon”更改为de api图标。
这是我正在工作的html部分:
<div>
<div class="w-location">
<h6 class="location-timezone">Timezone</h6>
</div>
<div class="w-icon">
<img id="temp-icon" src="imagenes/calendar.png">
</div>
<div class="w-temperature">
<p class="temp-degree">7 ° <span>C</span></p>
<p class="col-6 temp-description"> Freezen </p>
</div>
</div>
这是我的javasript,我从de api那里获取信息,并使用这些函数来更改html中的信息:
window.addEventListener('load',() => {
let long;
let lat;
let data;
let newIcon;
let locationTimezone = document.querySelector(".location-timezone");
let tempDescription = document.querySelector(".temp-description");
let tempDegree = document.querySelector(".temp-degree");
if (navigator) {
long = -87.627778;
lat = 41.881944;
const api = `http://api.weatherapi.com/v1/current.json?
key=db5d332edd014d29aa1175108201908&q=${lat},${long}`;
fetch(api)
.then(response => {
return response.json();
})
.then(function (json) {
data = json;
//set DOM elements from the API
locationTimezone.textContent = data.location.tz_id;
tempDescription.textContent = data.current.condition.text;
tempDegree.textContent = data.current.temp_c;
newIcon = data.current.condition.icon;
})
} else {
h1.textContent = "Geolocation not working"
}
});
如何在HTML中将newIcon信息设置为我的img(id =#temp-icon src =“”)?
谢谢!
解决方法
您可以使用Javascript对象或通过设置现有的img src来完成此操作。
以您的情况
document.getElementById("temp-icon").src = newIcon; //assuming newIcon is the URL
或者您可以创建一个新的Javascript Image对象并将图标图像源传递给它。
let iconImage = new Image();
iconImage.src = newIcon;
然后添加/附加iconImage
对象作为div的孩子。 (w-icon
)
https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image