You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NASA APOD API切换日期时媒体元素永久隐藏问题求助

解决NASA APOD API媒体切换时元素永久隐藏的问题

问题场景

我用NASA的APOD(每日天文图)API展示图片、视频及说明内容,需求是:查询不同日期时,只显示对应类型的元素——返回图片时显示img、隐藏iframe;返回视频时显示iframe、隐藏img。但实际运行出问题:元素设为display:none后,切换日期查询会永久隐藏,没法重新触发显示逻辑。

原实现代码

// 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}`)
    })

API返回的数据示例(图片类型)

{
    "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设为display:none,之后切换到图片日期时,只给img赋值了src,却没把它的display改回默认显示状态(比如block),导致img一直处于隐藏状态。

修复后的代码

// 从API获取数据
fetch(url)
  .then(res => res.json()) // 解析响应为JSON
  .then(data => {
    console.log(data);
    // 提前获取DOM元素,避免重复查询
    const imgElement = document.querySelector('img');
    const iframeElement = document.querySelector('iframe');
    const explanationElement = document.querySelector('h3');

    // 处理图片类型
    if (data.media_type === 'image') {
      imgElement.src = data.hdurl;
      imgElement.style.display = 'block'; // 显式设置图片为显示状态
      iframeElement.style.display = 'none'; // 隐藏视频元素
    } 
    // 处理视频类型
    else if (data.media_type === 'video') {
      iframeElement.src = data.url;
      iframeElement.style.display = 'block'; // 显式设置视频为显示状态
      imgElement.style.display = 'none'; // 隐藏图片元素
    } 
    // 异常情况处理
    else {
      alert('出错了,请重试');
    }

    // 更新说明文本
    explanationElement.innerText = data.explanation;
  })
  .catch(err => {
    console.log(`错误:${err}`);
  });

关键修改点

  • 提前缓存DOM元素,减少重复DOM查询,提升性能
  • 每个分支中同时处理显示和隐藏逻辑:不仅隐藏不需要的元素,还要显式设置需要展示的元素为显示状态(比如display: block,可根据你的布局调整为合适的值,比如inline-block)
  • 变量命名更清晰,代码可读性提升

内容的提问来源于stack exchange,提问作者JerseyDevil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 06:40:26