【问题标题】:Fetch an url img data and set it in a src attribute of an img in my html获取 url img 数据并将其设置在我的 html 中 img 的 src 属性中
【发布时间】:2020-12-12 09:02:06
【问题描述】:

我正在从天气 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 html image fetch src


    【解决方案1】:

    您可以使用 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

    【讨论】:

    • 谢谢!有用!但我在将此信息传递给我的 html 时遇到问题(对不起,我是新手!)。如果我控制台上的 console.log(iconImage) 以完美的方式显示信息 (cdn.weatherapi.com/weather/64x64/day/113.png">)。但是当我尝试将它粘贴到我的 html 中时它出现 [objectHTMLImageElement],这就是我的方式做到了:
    • document.getElementById("w_icon").innerHTML = iconImage;
    • 您可以从您的iconImage 获取图像src,然后使用上述代码之一
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    相关资源
    最近更新 更多