gpt4 book ai didi

javascript - 如何将数组属性写入 DOM 元素数组

转载 作者:行者123 更新时间:2023-12-01 13:11:12 25 4
gpt4 key购买 nike

我正在尝试将包含产品的列表添加到 HTML 页面。我试图用对象映射数组并将它们的属性分配给 HTML 元素数组。我不知道如何想出这个。

const productList = [{
photo: '../images/products/pizza/DSC_8740-002-Pitstsa-4-syra.jpg',
title: '4 сыра',
descriptiom: [
'more',
'description'
],
price: 125,
weight: 520,
}, {
photo: '../images/products/pizza/DhZBDqqwZzgTSYudncCZVQjOHHfQh9cs.jpg',
title: 'some title',
description: [
'some',
'description'
],
price: 140,
weight: 850,
}]

const products = document.querySelectorAll('.product')
const productItems = productList.map(element => {
//please help here
})
<div class="product-list">
<div class="product">
<img class="product__image" src="../images/products/pizza/chetyre-syra.jpg" alt="">
<p class="product__name">Product Name</p>
<p class="product__description">Product Description</p>
<p class="product__price">100.-</p>
<button class="product__btn"><i class="fas fa-plus"></i></button>
</div>
<div class="product">
<p class="product__name">Product Name</p>
<p class="product__description">Product Description</p>
<p class="product__price">100.-</p>
<button class="product__btn"><i class="fas fa-plus"></i></button>
</div>

最佳答案

试试这个。

function loadProducts() {
const productList = [
{
photo: "../images/products/pizza/DSC_8740-002-Pitstsa-4-syra.jpg",
title: "4 сыра",
description: ["more", "description"],
price: 125,
weight: 520
},
{
photo:
"../images/products/pizza/DhZBDqqwZzgTSYudncCZVQjOHHfQh9cs.jpg",
title: "some title",
description: ["some", "description"],
price: 140,
weight: 850
}
];

const productItems = productList.map(element => {
let elem = document.createElement("div");
elem.setAttribute("class", "product");
let productItem = `
<img class="product__image" src="${element.photo}" alt="">
<p class="product__name">${element.title}</p>
<p class="product__description">${element.description.join( " " )}</p>
<p class="product__price">${element.price}</p>
<button class="product__btn"><i class="fas fa-plus"></i></button>
`;
elem.innerHTML = productItem;
return elem;
});

let container = document.querySelector(".product-list");
for (const product of productItems) {
container.append(product);
}
}
loadProducts();
 <div class="product-list"></div>

关于javascript - 如何将数组属性写入 DOM 元素数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59811754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com