使用JavaScript动态显示数组数据
我正在建立一个模拟的电子商务商店,在那里我试图让功能正常工作。目前,我有一个商店页面,如果我单击“添加到购物车”,将调用一个函数,将相应的产品添加到一个名为cartItems的数组(“购物车”) 问题是试图在购物车页面上显示该数组中保存的数据。我想建立一个表,既可以容纳多种产品,也可以风格化。我不完全确定如何做到这一点 我已经通读并尝试使用stringify,但收效甚微。我认为这是最好的选择,但我不确定使用JavaScript动态显示数组数据,javascript,html,css,Javascript,Html,Css,我正在建立一个模拟的电子商务商店,在那里我试图让功能正常工作。目前,我有一个商店页面,如果我单击“添加到购物车”,将调用一个函数,将相应的产品添加到一个名为cartItems的数组(“购物车”) 问题是试图在购物车页面上显示该数组中保存的数据。我想建立一个表,既可以容纳多种产品,也可以风格化。我不完全确定如何做到这一点 我已经通读并尝试使用stringify,但收效甚微。我认为这是最好的选择,但我不确定 This is code which adds the product to the car
This is code which adds the product to the cart
let cartItems = [];
const addToCartBtns = [...document.querySelectorAll(".atc-button")];
addToCartBtns.forEach(button => {
button.addEventListener("click", function(){
const productSKU = button.getAttribute('data-product-id'),
product = catalog.findById(productSKU);
cartItems.push({
sku: productSKU,
qty: 1,
productInfo: product
});
cart页面上的一个表,其中包含当前位于cartItems数组中的所有产品。理想情况下,这也是一种从阵列/购物车中删除产品并更改数量的方法。这是一个如何使用es6模板字符串在表中动态显示数据的示例
content.innerHTML = `<table id='productTable'>
<tr>
<th>name</th>
<th>description</th>
<th>price</th>
<th>quantity</th>
<th>remove</th>
</tr>`
+
(cartItems.map(createProductTableRow).join('\n'))
+
`</table> `;
function createProductTableRow(product) {
return `
<tr>
<td>${product.productInfo.title}</td>
<td>${product.productInfo.description}</td>
<td>${product.productInfo.price}</td>
<td>${product.qty}</td>
<td><button class='remove'>Remove Item</button></td>
</tr>`;
}
content.innerHTML=`
名称
描述
价格
量
去除
`
+
(cartItems.map(createProductTableRow.join('\n'))
+
` `;
函数createProductTableRow(产品){
返回`
${product.productInfo.title}
${product.productInfo.description}
${product.productInfo.price}
${product.qty}
删除项目
`;
}
您可以通过css使用表的id“productTable”设置表的样式。
每行的最后一个条目还包含一个动态创建的“remove”类按钮,您可以为其编写javascript代码来删除项目。同样只是一个示例,您可以使用此方法动态创建任意html标记。我将构建一个“cart”和一个“cart\u item”类。这两个类都有
view()
方法,在给定对象属性的情况下,这些方法只会创建和输出您想要查看的HTML。您将有一个购物车项目对象列表作为购物车对象的属性。cartview
方法将是一个html表。您可以使用for
循环遍历所有购物车项目,并为每个项目调用view
方法。然后在产品页面上调用购物车的视图
方法。为视图方法中使用的html类创建css文件。您可以轻松地向购物车类添加用于显示“删除”和“添加”按钮(可在“视图”方法中使用)的方法,以及用于处理这些操作的方法。
This is what the array data looks like once added
0:
productInfo: Product
description: "Sed portitor lectus nibh. Curabitur aliquet quam id
dui posuere blandit. Lorem ipsumo dolor sit amet, consictetur
adipiscing elit."
id: "00001"
imgUrl: "https://source.unsplash.com/9489sFfgk4c/1000x1000"
price: 1999
readMore: "st-helen-chair.html"
title: "St. Helen Chair"
__proto__: Object
qty: 1
sku: "00001"
content.innerHTML = `<table id='productTable'>
<tr>
<th>name</th>
<th>description</th>
<th>price</th>
<th>quantity</th>
<th>remove</th>
</tr>`
+
(cartItems.map(createProductTableRow).join('\n'))
+
`</table> `;
function createProductTableRow(product) {
return `
<tr>
<td>${product.productInfo.title}</td>
<td>${product.productInfo.description}</td>
<td>${product.productInfo.price}</td>
<td>${product.qty}</td>
<td><button class='remove'>Remove Item</button></td>
</tr>`;
}