繁体   English   中英

当 API 不返回任何数据时隐藏元素

[英]Hide elements when API doesn't return any data

我正在使用 Nasa API APOD 天文图片 我想显示图片和解释。 在 2/3/21,他们展示了一段视频。 如果他们搜索一个日期然后搜索另一个日期,我想隐藏没有收到数据的元素。 我得到的结果是,一旦没有收到数据,该元素就会永久隐藏,而不是仅隐藏未收到的元素。 这个想法是,如果数据是图像,则显示 img 并隐藏 iframe。否则,如果数据是视频,则显示 iframe 并隐藏图像。 如果我在元素被隐藏或显示后搜索多个日期:“无”,该元素现在将永久隐藏,而不是每次运行新搜索时都通过 if 语句。

// fetch response from api
fetch(url)
    .then(res => res.json()) //parse response as JSON
    .then(data => {
        console.log(data)
        // display image in the dom
        if(data.media_type ==='image') {
            document.querySelector('img').src = data.hdurl
            document.querySelector('iframe').style.display = "none"
        // display video in the dom
        }else if (data.media_type === 'video') {
            document.querySelector('iframe').src = data.url
            document.querySelector('img').style.display = "none"
        } else {
            alert('Error, please try again')
        }

        // display explanation of image / video
        document.querySelector('h3').innerText = data.explanation
    })
    .catch(err => {
        console.log(`error ${err}`)
    })
}

收到的数据(对象):

{
    date: "2021-02-04",
    explanation: "Fifty years ago this Friday.....",
    hdurl: "https://apod.nasa.gov/apod/image,/2102/a14pan9335-43emj.jpg",
    media_type: "image",
    service_version: "v1",
    title: "Apollo 14: A View from Antares",
    url: "https://apod.nasa.gov/apod/image/2102/a14pan9335-43emj_900.jpg"
}

您需要更改代码,以便在要显示图像时显示img元素,并隐藏iframe 如果要显示视频,则相反 - 您需要显示iframe并隐藏图像。

我还介绍了一个 CSS class none ,这是一个简单的display: none 这是为了您可以保留为元素设置的原始display值,而不是在将显示恢复为先前值时进行二次猜测。 当然,您不必这样做,但从长远来看,您可能会发现操作起来更容易。

这样的事情会起作用。

var image = document.querySelector("img");
var ifr = document.querySelector("iframe");
var info = document.querySelector("h3");

fetch(url)
  .then(res => res.json()) //parse response as JSON
  .then(data => {
      console.log(data);
      // display image in the dom
      if(data.media_type ==='image') {
          // let's first set the source, and then display the image
          image.src = data.hdurl;
          image.classList.remove("none");

          // let's hide the iframe first, and then remove the source
          ifr.classList.add("none");
          ifr.src = "";
      // display video in the dom
      } else if (data.media_type === 'video') {
          // similar as above - hide first, remove source, and the opposite
          // for iframe
          image.classList.add("none");
          image.src = "";

          ifr.src = data.url;
          ifr.classList.remove("none");
      } else {
          alert('Error, please try again');
      }

      // display explanation of image / video
      info.innerText = data.explanation;
  })
  .catch(err => {
      console.log(`error ${err}`);
  });

暂无
暂无

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

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