聪明人!所以,我正在学习如何使用API,我很难为它实现一个搜索框。正如你在下面的代码中看到的,它应该有一个供用户搜索GIF的搜索字段和一个搜索另一个GIF但使用相同术语的按钮。明白了吗?在这段代码中,您可以看到按钮正在工作,它使用单词“fetch”(该单词位于gif的末尾)返回另一个gif。
我不知道如何使用搜索框。我尝试使用${search.value}而不是随机来获取search的值,它可以工作(尽管返回一个TypeError不能读取未定义的属性'fixed_height‘)。但是,我该如何让该按钮使用用户在搜索中传递的值来请求另一个gif呢?我希望这不是太混乱,我感谢任何回应。
我的代码:
const img = document.querySelector('img');
const btn = document.querySelector('button');
const form = document.querySelector('.form');
const search = document.getElementById('search');
btn.addEventListener('click', loadGIF);
form.addEventListener('submit', loadGIF);
function loadGIF(e) {
e.preventDefault();
fetch(
'https://api.giphy.com/v1/gifs/translate?api_key=g3TEgnU2pGODGJrcvHcn36HwOhK3E8l9&s=random', {
mode: 'cors'
}
)
.then(function(response) {
return response.json();
})
.then(function(json) {
img.src = json.data.images.fixed_height.url;
})
.catch(function(err) {
console.log(err);
});
}
document.addEventListener('DOMContentLoaded', loadGIF);body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 90vh;
}
.form {
margin-bottom: 0.8rem;
}
button {
margin-top: 0.5rem;
background: rgb(54, 43, 209);
border: none;
padding: 0.5rem 1rem;
color: white;
font-size: 1.2rem;
cursor: pointer;
}
button:hover {
background: rgb(90, 80, 240);
}<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<form class="form">
<label for="search">Search GIF:</label>
<input type="text" id="search" />
</form>
<img src="#" />
<button>Another GIF</button>
发布于 2021-02-11 08:32:02
您只需获取该值并在URL中使用它。
您可以使用search.value从输入中获取值。
const img = document.querySelector('img');
const btn = document.querySelector('button');
const form = document.querySelector('.form');
const search = document.getElementById('search');
btn.addEventListener('click', loadGIF);
form.addEventListener('submit', loadGIF);
function loadGIF(e) {
var searchValue = search.value; // Create a variable with the input value
if (!searchValue) {
searchValue = 'random'; // If the value is empty, we put the 'random' value
}
e.preventDefault();
fetch(
'https://api.giphy.com/v1/gifs/translate?api_key=g3TEgnU2pGODGJrcvHcn36HwOhK3E8l9&s='+searchValue, { // Here we use the variable searchValue with what was typed by the user.
mode: 'cors'
}
)
.then(function(response) {
return response.json();
})
.then(function(json) {
img.src = json.data.images.fixed_height.url;
})
.catch(function(err) {
console.log(err);
});
}
document.addEventListener('DOMContentLoaded', loadGIF);“虽然return a TypeError不能读取未定义的属性'fixed_height‘”
出现此问题的原因是,当您使用空值通过gif进行搜索时,不会返回任何内容。正因为如此,你需要将这个值设置为'random‘
https://stackoverflow.com/questions/66147015
复制相似问题