3 回答
TA贡献1871条经验 获得超13个赞
你有卡片作为一个对象,而你需要的东西就在这个对象内部。输出部分也是错误的,你没有card变量。所以,
function Mtg() {
fetch("https://api.magicthegathering.io/v1/cards")
.then((res) => res.json())
.then(({cards}) => { // destruct cards from object
let output = "";
cards.forEach((card) => {
output += `
<div>${card.name}</div>
<div>${card.imageUrl}</div>
`
});
document.getElementById("mtgCardsContainer").innerHTML = output;
});
}
TA贡献1816条经验 获得超4个赞
您的逻辑是正确的,您只是稍微偏离了响应的正确部分......
当您发出 fetch 请求时,您将返回一个 JSON 对象。您已选择为该对象卡命名。
在本例中,JSON 对象返回一个名为“cards”的对象,该对象本身包含一个也称为“cards”的数组,因此为了访问该数组,您需要定位以下内容:
cards.cards.forEach((item, index) => {
console.log(item)
});
为了使您的代码更具可读性并减少混乱,您可能希望更改与返回的 JSON 对象相关的卡片变量的名称......
.then((data) => {
let output = "";
data.cards.forEach((item, index) => {
console.log(item)
output += `
<div>${item.name}</div>
<div>${item.imageUrl}</div>
`
});
...
});
TA贡献1911条经验 获得超7个赞
进行了一些重构并添加了一些评论。祝你好运:
/**
*
* @param card {Object}
* @returns {string} as HTML
*/
const cardTemplateHTML = (card) => {
return `
<div>${card.name}</div>
<div>${card.imageUrl}</div>
`
};
/**
*
* @param cards {Object}
*/
const renderCards = ({cards}) => { /*
note: your currently inject the object data that contains cards. So by using the modern syntax { cards }
you don't have to write 'const {cards} = data' or 'const cards = data.cards'
*/
const mtgCardsContainer = document.getElementById("mtgCardsContainer");
//generate HTML
const cardsHTML = cards.map(card => {
//generete the HTML for every entry
return cardTemplateHTML(card)
})
//merge the list together into one string
.join('');
//update DOM
mtgCardsContainer.innerHTML = cardsHTML;
}
const Mtg = () => {
// make fetch promise
fetch("https://api.magicthegathering.io/v1/cards")
//fetch result, returns new promise
.then((res) => res.json())
//fetch result, returns the rendered json data
.then((data) => renderCards(data)); /* return data example: data = { cards } */
}
//Load
document.addEventListener("DOMContentLoaded", Mtg);
<div id="mtgCardsContainer">
</div>
添加回答
举报