我是一个全栈开发的学生,我有一个事件侦听器,它在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=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);
});
});发布于 2021-04-20 03:44:17
那么,每次单击按钮时,您都会在容器内附加<img>标记(猜测是一个div),并使用id "response-container“。因此,您每次单击时都会从fetch中获得多个<img>。
因此,删除这行
responseContainerEl.appendChild(gifImg);您可以根据需要使用这3种方法中的任何一种
<img>标记,然后将其替换为replaceChild方法。<img>标记,然后在获取获取数据之后更新src,如下所示。<img>标记,然后在您每次单击该按钮时使用该id更新图像,它将获取不同的数据并根据数据更新src。对于2和3,每次单击按钮时更新src属性,向api发出请求并更新src。因为您在api调用中使用了random,所以每次调用它时,它都应该提供不同src。
document.getElementById('image').src = 'http://yourImagePathHere';此外,在promises中使用async和await语法设置src之前,请记住等待fetch api调用完成。
https://stackoverflow.com/questions/67167571
复制相似问题