【发布时间】:2020-07-25 16:03:23
【问题描述】:
我正在尝试使用我创建的 JSON 文件中的数据填充我的 HTML 模板。但是,我在该文件中有两个不同的数组,每个数组都包含多个对象,我不知道如何循环它们,因为我需要在单独的函数中循环它们。
如果我要在 JSON 文件中有一个大数组(“product”是我正在循环的数组),我在下面提供的 JS 代码可以工作,问题是我需要循环通过“glass”和单独的“木头”数组(在不同的功能中)。理想情况下,下面的 JS sn-p 会循环遍历“wood”数组。
我之前只从一个大数组中获取,所以我真的不知道如何解决这个问题。我知道这一定是超级简单的事情,但我被困住了,我会很感激我能得到的任何提示!提前致谢。
JS 文件:
function init() {
if (window.location.href.includes("wood")) {
fetchJson();
}
}
function fetchJson() {
fetch("products.json")
.then((res) => res.json())
.then(getWoodGallery(product));
}
function getWoodGallery(product) {
product.forEach(showWoodGallery);
}
/*--- display wood products ---*/
function showWoodGallery(product) {
console.log(product);
const woodTemplate = document.querySelector("#woodGalleryTemplate").content;
const woodTemplateCopy = woodTemplate.cloneNode(true);
const woodList = document.querySelector("#woodList");
woodTemplateCopy.querySelector("h2.name").textContent =
"Name: " + `${product.wood}`;
woodTemplateCopy.querySelector("p.dimensions").textContent =
"Dimensions: " + `${product.dimensions}`;
woodTemplateCopy.querySelector("h3.price").textContent =
"Price: " + `${product.price}`;
woodTemplateCopy.querySelector(".btn").textContent = `Buy Now`;
woodList.appendChild(woodTemplateCopy);
}
JSON 文件:
{
"wood": [
{
"id": "1",
"image": "http://mauriciolondono.be/wp/wp-content/uploads/2020/01/animales_1.jpeg",
"name": "Butterfly",
"dimensions": "30 x 45cm",
"price": 40,
"btn": ""
},
{
"id": "19",
"image": "http://mauriciolondono.be/wp/wp-content/uploads/2020/01/symmetry_4.jpeg",
"name": "Escher deconstructed",
"dimensions": "30 x 45cm",
"price": 20,
"btn": ""
}
],
"glass": [
{
"id": "20",
"image": "http://mauriciolondono.be/wp/wp-content/uploads/2020/01/vidrio_17.jpeg",
"name": "Juntos pero no revueltos",
"dimensions": "30 x 45cm",
"price": 20,
"btn": ""
},
{
"id": "21",
"image": "http://mauriciolondono.be/wp/wp-content/uploads/2020/01/vidrio_11.jpeg",
"name": "White & green",
"dimensions": "30 x 45cm",
"price": 20,
"btn": ""
}
]
}
【问题讨论】:
标签: javascript arrays json loops fetch