首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我如何让我的fetch调用返回相同大小的照片?

我如何让我的fetch调用返回相同大小的照片?
EN

Stack Overflow用户
提问于 2021-04-20 02:37:00
回答 1查看 74关注 0票数 1

我是一个全栈开发的学生,我有一个事件侦听器,它在Javascript中包含了一个fetch调用,但返回的gif都在它们自己的响应容器中。每次单击该按钮时,都会创建一个新的图像容器。我如何修复它,使gif只出现在同一个容器中?当我的按钮被点击时,我还想显示随机的照片流,而不仅仅是一个。任何帮助都是非常感谢的。

这是我的前两个按钮的代码。

代码语言:javascript
复制
window.addEventListener('fetch', function (event) {
  console.log("fetch add event listener");
});

natureBtn.addEventListener('click', function (event) {
  fetch(
    'https://api.giphy.com/v1/gifs/random?api_key=HvaacROi9w5oQCDYHSIk42eiDSIXH3FN&rating=g&tag=nature'
  )
    // Convert the response to JSON
    .then(function (response) {
      return response.json();
    })
    .then(function (response) {
      // Use 'querySelector' to get the ID of where the GIF will be displayed
      var responseContainerEl = document.querySelector('#response-container');
      // Create an '<img>' element
      var gifImg = document.createElement('img');
      // Set that element's 'src' attribute to the 'image_url' from our Giphy API response
      gifImg.setAttribute('src', response.data.image_url);
      // Append the '<img>' element to the page
      responseContainerEl.appendChild(gifImg);
    });
   

  });

  sportsBtn.addEventListener('click', function (event) {
    fetch(
      'https://api.giphy.com/v1/gifs/random?api_key=HvaacROi9w5oQCDYHSIk42eiDSIXH3FN&rating=g&tag=sports'
    )
      // Convert the response to JSON
      .then(function (response) {
        return response.json();
      })
      .then(function (response) {
        // Use 'querySelector' to get the ID of where the GIF will be displayed
        var responseContainerEl = document.querySelector('#response-container');
        // Create an '<img>' element
        var gifImg = document.createElement('img');
     
        // Set that element's 'src' attribute to the 'image_url' from our Giphy API response
        gifImg.setAttribute('src', response.data.image_url);
        // Append the '<img>' element to the page
        responseContainerEl.appendChild(gifImg);
      });
     
  
    });
EN

回答 1

Stack Overflow用户

发布于 2021-04-20 03:44:17

那么,每次单击按钮时,您都会在容器内附加<img>标记(猜测是一个div),并使用id "response-container“。因此,您每次单击时都会从fetch中获得多个<img>

因此,删除这行

代码语言:javascript
复制
 responseContainerEl.appendChild(gifImg);

您可以根据需要使用这3种方法中的任何一种

  1. 使用replaceChild()代替appendChild(),但这将要求您在开始时创建一个<img>标记,然后将其替换为replaceChild方法。

  1. 您可以在调用fetch之前使用javascript创建一个<img>标记,然后在获取获取数据之后更新src,如下所示。

  1. 在html中创建一个带有id的<img>标记,然后在您每次单击该按钮时使用该id更新图像,它将获取不同的数据并根据数据更新src。

对于2和3,每次单击按钮时更新src属性,向api发出请求并更新src。因为您在api调用中使用了random,所以每次调用它时,它都应该提供不同src。

代码语言:javascript
复制
document.getElementById('image').src = 'http://yourImagePathHere';

此外,在promises中使用asyncawait语法设置src之前,请记住等待fetch api调用完成。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67167571

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档