[英]Fetch an url img data and set it in a src attribute of an img in my html
我正在從天氣 api 信息中獲取我的應用程序。 我設法在我的 html 中為“位置-時區”、“溫度-度”和“溫度-描述”帶來和更改信息; 但我無法將 mi“溫度圖標”更改為 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.