首页 > 解决方案 > 使用 JavaScript 动态显示数组数据

问题描述

我正在建立一个模拟电子商务商店,我试图让功能正常工作。目前,我有一个商店页面,如果单击“添加到购物车”,则会调用一个函数,该函数将相应的产品添加到名为 cartItems 的数组(“购物车”)中。

问题是试图在购物车页面上显示该数组中保存的数据。我想建立一个既可以容纳多种产品又可以风格化的桌子。我不完全确定如何实现这一目标。

我已经通读并尝试使用 stringify,但收效甚微。我认为这是最好的选择,但不确定。

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
    });
This is the information which is pushed to the array. 

class Product {
  constructor(propsObj) {
    this.id = propsObj.id;
    this.title = propsObj.title;
    this.description = propsObj.description;
    this.imgUrl = propsObj.imgUrl;
    this.price = propsObj.price;
    this.readMore = propsObj.readMore;
  }
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"

购物车页面上的表格,其中包括当前位于 cartItems 数组中的所有产品。理想情况下,这也是一种从阵列/购物车中取出产品并改变数量的方法。

标签: javascripthtmlcss

解决方案


这将是一个如何使用 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>`;
}

您可以通过 css 使用它的 id "productTable" 设置表格样式。每行的最后一个条目还包含一个动态创建的“删除”类按钮,您可以为此编写 javascript 代码来删除项目。同样只是一个示例,您可以使用此方法动态创建任意 html 标记。


推荐阅读