如何将JSON图像值分配给HTML img标记

时间:2016-03-26 13:49:00

标签: javascript html json

这是成功显示图片的完整网址。

http://openweathermap.org/img/w/04d.png

注意,JSON属性“icon”提供的值为“04d”,我可以将其放入url中以便使用它。

  

作为参考,为了显示JSON路径是正确的,以下是我从存储图像的相同JSON属性中成功显示文本的方法。

     

document.getElementById(“weatherDescriptionData”)。innerHTML = data.weather [0] .description;

这是HTML img标记

<img src="" id="weatherIconData"></div>

这是我尝试显示图像失败的第一种方法。 (向右滚动)

document.getElementById("weatherIconData").src = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png";

这是我尝试显示图像失败的第二种方法。

$("#weatherIconData").prop('src', "http://openweathermap.org/img/w/" + data.weather[0].icon  + ".png");

我查了一下,发现了

console.log(data.weather[0].icon);

实际上确实返回04d。

如何在HTML视图中显示JSON中提供的图像?

3 个答案:

答案 0 :(得分:3)

尝试jquery .attr

$("#weatherIconData").attr('src', 'http://openweathermap.org/img/w/' + data.weather[0].icon  + '.png');

您的html代码也以<img>开头,但</div>关闭,并以<img id="" src="" />

结束

&#13;
&#13;
$(function() {
  var data = {
    weather: [{
      icon: '04d'
    }]
  };
  
  $("#weatherIconData").attr('src', 'http://openweathermap.org/img/w/' + data.weather[0].icon + '.png');
});
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<img src="" id="weatherIconData"/>
</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您没有关闭<img />标记。

<img id="weatherIconData" />

jQuery可能解决了这个问题,但不像@ user2950720建议的那样是正确的解决方案。没有理由$('#id')应该使用document.getElementById('id')

var data = {
  weather: [{
    icon: '04d'
  }]
};

document.getElementById("weatherIconData").src = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png";;
<img src="" id="weatherIconData">

答案 2 :(得分:-1)

使用attr而不是prop。的 Working Fiddle

$("#weatherIconData").attr('src', "....");