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

如何让Waifu API返回的图片在页面中正常显示?

Waifu API图片渲染问题解决

问题描述

调用Waifu API时,控制台能正常获取JSON数据,也能看到图片地址,但点击按钮后页面无法正确显示图片。

问题根源

  • DOM元素选择错误:你选中了<div id="waifuImage">容器,但实际需要设置图片的是容器内的<img id="waifus">标签。div元素没有src属性,所以设置waifuImage.src完全无效。
  • API数据结构处理错误:Waifu API返回的图片地址在res.images数组的每个元素的url字段里,你错误尝试访问不存在的res.url字段。
  • 冗余代码干扰:makeImages函数逻辑不符合当前API的返回结构,且从未被调用;最后waifus = waifuImage属于无效冗余代码。

修正后的代码

HTML(无需修改)

<!-- ---waifuthingy----- -->
<div id="waifuContainer" class="container mt-5 text-center">
    <h1 class="display-5 text-warning" id="dadJokeFont">Click for waifu:</h1>
    <button id="waifuButton" class="btn btn-warning mt-5">uWu</button>
    <div id="waifuImage" >
        <img id="waifus" src="" alt=""> 
    </div>
</div>
<!-- ----letmebe---- -->

JavaScript

// Waifu Image API
const waifuImgElement = document.querySelector('#waifus');
const waifuButton = document.querySelector('#waifuButton');

waifuButton.addEventListener('click', () => {
    fetch('https://api.waifu.im/random')
        .then(res => res.json())
        .then(res => {
            // 取返回数组中第一个图片的地址
            const imageUrl = res.images[0].url;
            waifuImgElement.src = imageUrl;
            waifuImgElement.alt = 'Waifu Image';
        })
        .catch(err => console.log(err))
})

关键修改说明

  • 将DOM选择器改为#waifus,直接选中需要渲染的img标签。
  • 正确读取API返回的res.images[0].url,接口返回的是图片数组,取第一个元素的地址即可。
  • 给img标签设置alt属性,符合网页语义化要求。
  • 删除了无意义的makeImages函数和冗余赋值语句。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 17:46:08