【发布时间】:2021-05-28 15:06:48
【问题描述】:
我正在使用 marvel 的 api 制作一个应用程序,在这个应用程序中我试图放置一个搜索栏,但我没有得到它。
每次我尝试在此 api 中搜索名称时,函数 Search() 在 html 中未定义。
我不明白html中没有定义函数。
我能做些什么来改变这个?
const timeStamp = "1622146184";
const privateKey = "somekey";
const publicKey = "someotherkey";
const md5 = "b34f17bceca201652c24e9aa21777da9";
const Hero = document.querySelector('article');
const input = document.getElementById('myInput');
fetch(`http://gateway.marvel.com/v1/public/characters?ts=${timeStamp}&apikey=${publicKey}&hash=${md5}&limit=6`).then((response)=> {
return response.json();
}).then((jsonParsed)=>{
jsonParsed.data.results.forEach(element => {
const srcImage = element.thumbnail.path + '.' + element.thumbnail.extension;
const nameHero = element.name;
createHero(srcImage, nameHero, Hero);
},
function Search() {
// Declare variables
const filter = input.value.toUpperCase();
const textName2 = nameHero;
// Loop through all textName2st items, and hide those who don't match the search query
for (i = 0; i <= textName2.length; i++) {
const p = textName2[i].getElementsByTagName("p")[0];
txtValue = p.textContent || p.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
textName2[i].style.display = "";
} else {
textName2[i].style.display = "none";
}
}
})
console.log(jsonParsed);
})
function createHero(srcImage, nameHero, divToAppend){
const divPai = document.createElement('section');
const textName = document.createElement('p');
const img = document.createElement('img');
textName.textContent = nameHero;
img.src= srcImage;
divPai.appendChild(img);
divPai.appendChild(textName);
divToAppend.appendChild(divPai);
divPai.classList.add("personagem");
}
<main>
<input type="text" id="myInput" onkeyup="Search()" placeholder="Search for names.." />
<article id="herois"></article>
</main>
【问题讨论】:
-
您可能想要删除您的公钥和私钥
-
如果这确实是您的代码,那么您缺少一些关闭
}和)。所以你的Search函数是在fetch的then处理程序中定义的,因此当然不是全局可用的。
标签: javascript html api for-loop onkeyup