简体   繁体   English

图片API src成 <img> 用jQuery

[英]image API src into <img> with jquery

I'm starting out with jquery and json, working on a weather app using OpenWeatherMap's API. 我从jquery和json开始,使用OpenWeatherMap的API开发天气应用。 I'm trying to pass an icon src to be displayed with an img tag. 我正在尝试传递要与img标签一起显示的图标 src。 I understand something analogous has been asked before (which was my model for the code below), but I'm not seeing a change in <img> upon inspection. 我了解之前曾有人提出过类似的要求(这是我下面的代码模型),但是经检查我没有看到<img>的变化。

In my view I have <img id="icon" src="#"> , and this is my jquery: 在我看来,我有<img id="icon" src="#"> ,这是我的jquery:

$(document).ready(function() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var lati = position.coords.latitude;
      var longi = position.coords.longitude;
      var address = "http://api.openweathermap.org/data/2.5/weather?lat=" + lati +"&lon=" + longi + "&APPID=****";

      $.getJSON(address, function(json) {
        var iconSrc = "http://openweathermap.org/img/w/" +json.weather.icon +".png";
        $('#icon img').attr('src', iconSrc);
      });
    });
  }
}); 

$('#icon img').attr('src', iconSrc); selection is not the correct one for your example 选择不适合您的示例

you are trying to select an img element that is a child of an element with id icon #icon 您正在尝试选择一个具有id图标#icon的元素的子元素的img元素

select only with the id 仅选择ID

$('#icon').attr('src', iconSrc);

Remember id's should be unique, so if you have multiple img tags to populate use classes 请记住,id应该是唯一的,因此,如果您有多个img标签来填充使用类,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM