javascript - 如何让我的 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);
});
});
解决方案
<img>
好吧,每次单击按钮时,您都在容器内附加标签(猜测是一个 div),ID 为“response-container”。<img>
因此,每次单击时,您都会从 fetch中获得倍数。
所以,删除线
responseContainerEl.appendChild(gifImg);
您可以根据需要使用 3 种方法中的任何一种
使用 replaceChild() 而不是 appendChild() ,但这需要您
<img>
在开始时创建一个标签,然后用 replaceChild 方法替换它。您可以在调用 fetch 之前使用 javascript 创建
<img>
标签,然后在获取 fetch 数据后更新 src,如下所示。在 html 中创建一个
<img>
带有 id 的标签,然后在您单击按钮时使用该 id 更新图像,它将获取不同的数据并根据数据更新 src。
对于 2 和 3,每次单击按钮向 api 发出请求并更新 src 时,都会更新 src 属性。由于您在 api 调用中使用了 random ,因此每次调用它时都应该为您提供不同的 src 。
document.getElementById('image').src = 'http://yourImagePathHere';
另外,请记住等待 fetch api 调用完成,然后再在 promise 中设置 src 使用async
和await
语法。
推荐阅读
- java - XSSFCell -> 如何从 long 中获取间隔时间值
- python - 如何修复:AttributeError:模块“整洁”没有属性“配置”
- android - 将增强现实和 3D 对象实施到移动应用程序中,
- c++ - C++ 入门 5 版:shared_ptr 从 uniqe_ptr 初始化?
- java - 卡在数独作业的回溯步骤上
- json - 寻找将通过 websocket 接收的 JSON 数据显示到 Xcode/Swift 动态表中的最有效方法
- catboost - CatBoost RandomizedSearch 停止并找出它的超参数
- python - 从 input_t(实际上是三个数字并充当特征)和 output_t 作为输出创建一个数据框
- javascript - JS文件无法访问laravel变量
- three.js - 如何在three.js上通过addEventListener动态更新set.position.x?