簡體   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