如何根据 JavaScript 中的对象 属性 显示图像

How to show image based on an object property in JavaScript

我有一个有四个键的变量。当图标键的值为01d时,我需要显示引用该值的图标,该图标位于img文件夹中。我怎样才能使这个有条件?

我有以下变量解构,下面我把它 return.

let [dt1, dt2, dt3, dt4, dt5, dt6, dt7, dt8] = urlJson returns:

{ dt: 1643803200, day: 12.84, description: 'clear sky', icon: '01d' }
{ dt: 1643889600, day: 14.56, description: 'overcast clouds', icon: '04d' }
{ dt: 1643976000, day: 14.85, description: 'overcast clouds', icon: '04d' }
{ dt: 1644062400, day: 14.41, description: 'broken clouds', icon: '04d' }
{ dt: 1644148800, day: 14.99, description: 'clear sky', icon: '01d' }
{ dt: 1644235200, day: 15.68, description: 'few clouds', icon: '02d' }
{ dt: 1644321600, day: 14.95, description: 'broken clouds', icon: '04d' }
{ dt: 1644408000, day: 16.37, description: 'overcast clouds', icon: '04d' }

代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link id="mystylesheet" type="text/css" rel="stylesheet" href="style.css">

  <title>Document</title>
  <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>

<body>
  <div id="wrapper">
    <h1 class="city"></h1>
    <h2><span id="tags">0</span>ºC</h2>
  </div>
  <script>
    const urlJsonString = $.getJSON('https://api.openweathermap.org/data/2.5/onecall?lat=38.7267&lon=-9.1403&exclude=current,hourly,minutely,alerts&units=metric&appid={APPID}', function (data) {
      let urlJson = data.daily.map(({ dt, temp: { day }, weather: [{ description, icon }] }) => ({ dt, day, description, icon }))
      let [dt1, dt2, dt3, dt4, dt5, dt6, dt7, dt8] = urlJson
      var date = dt1.dt

      let result = `Temperature: ${dt1.day} ºC<br>
      Dia: ${date}<br>
      ${dt1.icon}`
      $(".city").html(result);
    });
  </script>
</body>

</html>

看看这是否适合您。我没有密钥访问这个 API,所以我用你的虚构数据做了。

请确保您的 'icon' 是您的图片 URL

https://jsfiddle.net/ep9hsxLf/

let urlJson = [
  { dt: 1643803200, day: 12.84, description: 'clear sky', icon: '01d' },
  { dt: 1643889600, day: 14.56, description: 'overcast clouds', icon: '04d' },
  { dt: 1643976000, day: 14.85, description: 'overcast clouds', icon: '04d' },
  { dt: 1644062400, day: 14.41, description: 'broken clouds', icon: '04d' },
  { dt: 1644148800, day: 14.99, description: 'clear sky', icon: '01d' },
  { dt: 1644235200, day: 15.68, description: 'few clouds', icon: '02d' },
  { dt: 1644321600, day: 14.95, description: 'broken clouds', icon: '04d' },
  { dt: 1644408000, day: 16.37, description: 'overcast clouds', icon: '04d' }
]

var htmlResult = '';

urlJson.forEach(item => {

  var date = new Date(item.dt)

  htmlResult += `Temperature: ${item.day} ºC<br>
  Dia: ${date}<br>
  ${item.icon}<br><br>`
});


$(".city").html(htmlResult);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div class="city"></div>