如何让抓取调用返回相同位置/尺寸的照片?



我是一个全栈开发学生,我有一个事件侦听器,其中包括Javascript中的获取调用,但是返回的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);
});


});

好吧,每次单击按钮时,您都会将带有id"response-container"的<img>标签附加到容器内(猜测div)。因此,每次点击时,您都会从抓取中获得多个<img>

因此,删除该行

responseContainerEl.appendChild(gifImg);

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

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

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

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

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

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

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

最新更新