这里可能是一个非常新手的问题,但无论如何这里都是。
我最近在我的网站上实现了这个 javascript的一个版本来显示博客文章摘要。
我想知道我需要进行哪些更改才能让它加载相同的字段但从单独的 JSON 文件中获取数据,而不是在同一个文件中包含类似 JSON 的信息?
我自己也尝试过,但我无法完全解决。
我在代码中与链接中的代码的唯一主要区别是我在最后的位中有“切片”而不是“加入”。
任何帮助将不胜感激,因为我对 Javascript 非常陌生。
const petsData = [
{
name: "Purrsloud",
species: "Cat",
favFoods: ["wet food", "dry food", "<strong>any</strong> food"],
birthYear: 2016,
photo: "https://learnwebcode.github.io/json-example/images/cat-2.jpg"
},
{
name: "Barksalot",
species: "Dog",
birthYear: 2008,
photo: "https://learnwebcode.github.io/json-example/images/dog-1.jpg"
},
{
name: "Meowsalot",
species: "Cat",
favFoods: ["tuna", "catnip", "celery"],
birthYear: 2012,
photo: "https://learnwebcode.github.io/json-example/images/cat-1.jpg"
}
];
function age(birthYear) {
let calculatedAge = new Date().getFullYear() - birthYear;
if (calculatedAge == 1) {
return "1 year old";
} else if (calculatedAge == 0) {
return "Baby";
} else {
return `${calculatedAge} years old`;
}
}
function foods(foods) {
return `
<h4>Favorite Foods</h4>
<ul class="foods-list">
${foods.map(food => `<li>${food}</li>`).join("")}
</ul>
`;
}
function petTemplate(pet) {
return `
<div class="animal">
<img class="pet-photo" src="${pet.photo}">
<h2 class="pet-name">${pet.name} <span class="species">(${pet.species})</span></h2>
<p><strong>Age:</strong> ${age(pet.birthYear)}</p>
${pet.favFoods ? foods(pet.favFoods) : ""}
</div>
`;
}
document.getElementById("app").innerHTML = `
<h1 class="app-title">Pets (${petsData.length} results)</h1>
${petsData.map(petTemplate).slice(0, 2)}
<p class="footer">These ${petsData.length} pets were added recently. Check back soon for updates.</p>
`;
扬帆大鱼
慕容3067478
慕后森
随时随地看视频慕课网APP
相关分类