刚接触 JS,正在课堂上做一个项目。我们正在与 pokeAPI 网站合作,将所有神奇宝贝加载到具有正确 API url 的表中。我以为我走在正确的轨道上,但加载到表中的唯一内容显示未定义。我只参加入门课程,所以请尽可能保持基础!
window.onload = () => {
fetchData();
tableArea;
}
async function fetchData() {
const url = 'https://pokeapi.co/api/v2/pokemon';
const response = await fetch(url);
const data = await response.json();
const pokeData = JSON.stringify(data);
//console.log(pokeData);
tableArea(pokeData);
}
function tableArea(pokeData){
const tableBody = document.querySelector("#pokemon-list")
for (let record of pokeData) {
const pokeName = record.name;
const pokeUrl = record.url;
tableBody.innerHTML += `<tr><td>${pokeName}</td><td>${pokeUrl}</td></tr>`;
}
}
这不起作用,因为
JSON.stringify(data
)会将您的数据转换为字符串,并且您不能以这种方式循环字符串
window.onload = () => {
fetchData();
}
async function fetchData() {
const url = 'https://pokeapi.co/api/v2/pokemon?limit=151'; // Added a limit to fetch 151 pokemon
const response = await fetch(url);
const data = await response.json();
tableArea(data.results); // Pass only the array of pokemon to tableArea
}
function tableArea(pokeData) {
const tableBody = document.querySelector("#pokemon-list");
for (let record of pokeData) {
const pokeName = record.name;
const pokeUrl = record.url;
tableBody.innerHTML += `<tr><td>${pokeName}</td><td>${pokeUrl}</td></tr>`;
}
}