首页 > 解决方案 > 如何让我的 fetch 调用返回相同位置/尺寸的照片?

问题描述

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

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

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=MY_API_KEY&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=MY_API_KEY&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);
      });
     
  
    });

标签: javascriptfetch

解决方案


<img>好吧,每次单击按钮时,您都在容器内附加标签(猜测是一个 div),ID 为“response-container”。<img>因此,每次单击时,您都会从 fetch中获得倍数。

所以,删除线

 responseContainerEl.appendChild(gifImg);

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

  1. 使用 replaceChild() 而不是 appendChild() ,但这需要您<img>在开始时创建一个标签,然后用 replaceChild 方法替换它。

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

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

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

document.getElementById('image').src = 'http://yourImagePathHere';

另外,请记住等待 fetch api 调用完成,然后再在 promise 中设置 src 使用asyncawait语法。


推荐阅读