在购物车页面上显示购物车/阵列

时间:2019-08-22 19:51:42

标签: javascript html css bootstrap-4

// This is the JavaScript file of my project. This file is responsible for a
// few processes. Namely: Setting up all of the JSON data for the store, populating
// the shop page with the added product data, generating the shop page product cards,
// facilitating the adding of cart data to an array so that it can be used on the
// cart page and for alerting the user on updates and changes to their cart.

// This object, catalogJSON, stores all of the product data related to the store
// including id, title, description, image URL and price.

const catalogJSON = {
  products: [
    {
      id: '00001',
      title: 'St. Helen Chair',
      description: `Sed portitor lectus nibh. Curabitur aliquet quam id dui posuere blandit. Lorem ipsumo dolor sit amet, consictetur adipiscing elit.`,
      imgUrl: 'https://source.unsplash.com/9489sFfgk4c/1000x1000',
      price: 1999,
      readMore: 'st-helen-chair.html'
    },
    {
      id: '00002',
      title: 'Crane Neck Lamp',
      description: `Sed portitor lectus nibh. Curabitur aliquet quam id dui posuere blandit. Lorem ipsumo dolor sit amet, consictetur adipiscing elit.`,
      imgUrl: 'https://source.unsplash.com/0kjNpxQ6dPQ/1000x1000',
      price: 499,
      readMore: 'crane-neck-lamp.html'
    },
    {
      id: '00003',
      title: 'His & Hers Mugs',
      description: `Sed portitor lectus nibh. Curabitur aliquet quam id dui posuere blandit. Lorem ipsumo dolor sit amet, consictetur adipiscing elit.`,
      imgUrl: 'https://source.unsplash.com/qVg2lhK4sVY/1000x1000',
      price: 249,
      readMore: 'his-and-hers-mugs.html'
    },
    {
      id: '00004',
      title: 'Minimalistic Frame',
      description: 'Sed portitor lectus nibh. Curabitur aliquet quam id dui posuere blandit. Lorem ipsumo dolor sit amet, consictetur adipiscing elit.',
      imgUrl: 'https://source.unsplash.com/XwdSGEiOahM/1000x1000',
      price: 659,
      readMore: 'minimalistic-frame.html'
    },
    {
      id: '00005',
      title: 'City Cruiser',
      description: 'Sed portitor lectus nibh. Curabitur aliquet quam id dui posuere blandit. Lorem ipsumo dolor sit amet, consictetur adipiscing elit.',
      imgUrl: 'https://source.unsplash.com/igKjieyjcko/1000x1000',
      price: 8999,
      readMore: 'city-cruiser.html'
    }
  ]
};

// The Product class allows us to construct each one of our products and parse
// the unique values of each to it. Essentially, at this stage, we are describing
// what a product will look like in terms of its characteristics.

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;
  }

// Responsible for converting each JSON field to a string

  toString(){
    return `${this.title} (${this.id}: ${this.description} - R${this.price}`;
  }

// Using toHTML to create a template of the card layout that I would like to use
// 'template' is a string literal which means that I am able to embed expressions
// inside it (Like title, imgUrl, price, description and id).

  toHTML(){
    const template = `<div class="col col-12 col-sm-12 col-md-6 col-lg-4 pt-5 product-container">
        <div class="card text-white bg-dark">
          <img class="card-img-top img-fluid" src="${this.imgUrl}" alt="Image of ${this.title}">
          <div class="card-body">
            <h4 class="card-title">${this.title}</h4>
            <p class="card-subtitle text-muted">R${this.price}.00</p>
            <p class="card-text">${this.description}</p>
            <a href="${this.readMore}" class="btn btn-outline-light">Read More</a>
            <a href="#" data-product-id='${this.id}' class="atc-button btn btn-primary float-right">Add to Cart</a>
          </div>
        </div>
      </div>`;

// David Walsh's blog has a great post about using createRange and createContextualFragment
// to inject a templated string into your HTML without having to do any DOM hacking.
// Post here: https://davidwalsh.name/convert-html-stings-dom-nodes

      const domEl = document.createRange().createContextualFragment(template);
      domEl.querySelector('.atc-button').addEventListener('click', (evt) => console.log(evt.target.getAttribute(`data-product-id`)));

      return domEl;
  }
}

/* The Catalog class sets up the catalog that we need in order to present each
of the products that we have used the above template the firstly populate and then
build */

class Catalog {
  constructor(){
    this.catalog = [];
  }

  add(product) {
    const existingProduct = this.catalog.filter(item => item.id == product.id);

    if(existingProduct.length === 0){
      this.catalog.push(product);
    }
    return this;
  }

  remove(productId) {
    this.catalog = this.catalog.filter(item => item.id !== productId);
    return this;
  }

  findById(productId) {
    return this.catalog.filter(item => item.id===productId)[0];
  }
}

const catalogElement = document.querySelector('.product-container');
const catalog = new Catalog();
catalogJSON.products.forEach(product => {
  catalog.add(new Product(product));
});
catalog.catalog.forEach(product => {
  catalogElement.appendChild(product.toHTML());

})

// console.log(catalog);

/* cartItems is the array where all cart data will be added and stored. So, if a
user clicks on a button to add a product to their cart, the product will be added
to the cartItems array for me to reference later */

let cartItems = [];

// addToCartBtns will select all of the add to cart buttons on the shop page

const addToCartBtns = [...document.querySelectorAll(".atc-button")];

/* A forEach function will ensure that the same function runs on each button once
it is clicked (The product gets added to the cartItems array. */

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
    });
    // alert(${this.title} + " was added to your cart. Your new total is R" + ${this.price});
  });
});
console.log(cartItems);
/* PAGE BACKGROUNDS */

.index-background {
  height: calc(100vh - 56px);
  min-height: 500px;
  background-image: url('https://source.unsplash.com/kZLaSWR-7J4/1920x1080');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.login-background {
  height: calc(100vh - 56px);
  min-height: 500px;
  background-image: url('https://source.unsplash.com/0vw4InAC-yM/1920x1080');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.register-background {
  height: calc(100vh - 56px);
  min-height: 500px;
  background-image: url('https://source.unsplash.com/0vw4InAC-yM/1920x1080');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}


/* SETTING PAGE HEIGHTS */

.about-row {
  height: calc(100vh - 56px);
}

.shipping-row {
  height: calc(100vh - 56px);
}

.product-detail {
  height: calc(100vh - 56px);
}

.login-row {
  height: calc(100vh - 56px);
}

.register-row {
  height: calc(100vh - 56px);
}


/* EDITS TO CARDS */

.card-img-top {
    width: 100%;
    height: 15rem;
    object-fit: cover;
}

/* MISC. STYLING */

.features-list {
  list-style-type: circle;
  color: #A0A0A0;
}

.shipping-text {
  color: #A0A0A0;
}

/* BUTTON STATES */

.btn-primary:not(:disabled):not(.disabled):active {
  background: #343A40;
  border: 1px black solid;
  box-shadow: none;
}

.btn-primary:not(:disabled):not(.disabled):focus{
  box-shadow: none;
}

/* CART STYLING */

#itemsInCart {
  background-color: #6394F8;
  border-radius: 10px;
  color: white;
  display: none;
  font-size: 12px;
  line-height: 1;
  padding: 3px 7px;
  text-align: center;
  vertical-align: middle;
  white-space: nowrap;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Weyland's | Shop</title>
  <link rel="shortcut icon" href="">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <link rel="stylesheet" href="main.css">
</head>
<body>
  <nav class="navbar navbar-expand-sm navbar-light bg-light">
    <a class="navbar-brand" href="index.html">Weyland's</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>

      <div id="navbarNavDropdown" class="navbar-collapse collapse">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item"><a class="nav-link" href="about.html">About</a></li>
          <li class="nav-item"><a class="nav-link" href="shop.html">Shop</a></li>
          <li class="nav-item"><a class="nav-link" href="shipping.html">Shipping</a></li>
        </ul>

        <ul class="navbar-nav navbar-right">
          <li>
            <div class="dropdown-divider"></div>
          </li>
          <li class="nav-item"><a class="nav-link" href="login.html">Login</a></li>
          <li class="nav-item"><a class="nav-link" href="register.html">Register</a></li>
          <li>
            <div class="dropdown-divider"></div>
          </li>
          <li>
            <span class="navbar-text d-none d-sm-block"> | </span>
          </li>
          <li class="nav item"><a class="nav-link" href="cart.html" id="cart">Cart <span id="itemsInCart"></span></a></li>
        </ul>
      </div>
  </nav>

<!-- This is the part of the HTML that the JavaScript Catalog class latches onto
and where it injects the product cards -->

  <div class="container">
    <div class="row product-container">
    </div>
  </div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="shopScripting.js"></script>
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>

我已经建立了一个小型的“电子商务商店”。在一些帮助下,我设法使购物车功能正常运行(在其中单击“添加到购物车”,然后将产品添加到购物车(依次存储在数组中)。现在,我试图在购物车上显示该数组购物车页面。

我尝试在“购物车”页面上创建一个容器,然后将该容器作为函数的一部分进行调用。然后将数组推送到此容器。事实证明这很困难。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Weyland's | Shop</title>
  <link rel="shortcut icon" href="">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <link rel="stylesheet" href="main.css">
</head>
<body>
  <nav class="navbar navbar-expand-sm navbar-light bg-light">
    <a class="navbar-brand" href="index.html">Weyland's</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>

      <div id="navbarNavDropdown" class="navbar-collapse collapse">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item"><a class="nav-link" href="about.html">About</a></li>
          <li class="nav-item"><a class="nav-link" href="shop.html">Shop</a></li>
          <li class="nav-item"><a class="nav-link" href="shipping.html">Shipping</a></li>
        </ul>

        <ul class="navbar-nav navbar-right">
          <li>
            <div class="dropdown-divider"></div>
          </li>
          <li class="nav-item"><a class="nav-link" href="login.html">Login</a></li>
          <li class="nav-item"><a class="nav-link" href="register.html">Register</a></li>
          <li>
            <div class="dropdown-divider"></div>
          </li>
          <li>
            <span class="navbar-text d-none d-sm-block"> | </span>
          </li>
          <li class="nav item"><a class="nav-link" href="cart.html" id="cart">Cart <span id="itemsInCart"></span></a></li>
        </ul>
      </div>
  </nav>

<!-- This is the part of the HTML that the JavaScript Catalog class latches onto
and where it injects the product cards -->

  <div class="container">
    <div class="row product-container">
    </div>
  </div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="shopScripting.js"></script>
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Weyland's | Cart</title>

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <link rel="stylesheet" href="main.css">
</head>
<body>
  <nav class="navbar navbar-expand-sm navbar-light bg-light">
    <a class="navbar-brand" href="index.html">Weyland's</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>

      <div id="navbarNavDropdown" class="navbar-collapse collapse">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item"><a class="nav-link" href="about.html">About</a></li>
          <li class="nav-item"><a class="nav-link" href="shop.html">Shop</a></li>
          <li class="nav-item"><a class="nav-link" href="shipping.html">Shipping</a></li>
        </ul>

        <ul class="navbar-nav">
          <li>
            <div class="dropdown-divider"></div>
          </li>
          <li class="nav-item"><a class="nav-link" href="login.html">Login</a></li>
          <li class="nav-item"><a class="nav-link" href="register.html">Register</a></li>
          <li>
            <div class="dropdown-divider"></div>
          </li>
          <li>
            <span class="navbar-text d-none d-sm-block"> | </span>
          </li>
          <li class="nav-item"><a class="nav-link" href="cart.html">Cart</a></li>
          </ul>
      </div>
  </nav>

  <div class="container">
    <div class="row">
      <table id="cart-table"></table>
    </div>
  </div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="shopScripting.js"></script>
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
/* PAGE BACKGROUNDS */

.index-background {
  height: calc(100vh - 56px);
  min-height: 500px;
  background-image: url('https://source.unsplash.com/kZLaSWR-7J4/1920x1080');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.login-background {
  height: calc(100vh - 56px);
  min-height: 500px;
  background-image: url('https://source.unsplash.com/0vw4InAC-yM/1920x1080');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.register-background {
  height: calc(100vh - 56px);
  min-height: 500px;
  background-image: url('https://source.unsplash.com/0vw4InAC-yM/1920x1080');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}


/* SETTING PAGE HEIGHTS */

.about-row {
  height: calc(100vh - 56px);
}

.shipping-row {
  height: calc(100vh - 56px);
}

.product-detail {
  height: calc(100vh - 56px);
}

.login-row {
  height: calc(100vh - 56px);
}

.register-row {
  height: calc(100vh - 56px);
}


/* EDITS TO CARDS */

.card-img-top {
    width: 100%;
    height: 15rem;
    object-fit: cover;
}

/* MISC. STYLING */

.features-list {
  list-style-type: circle;
  color: #A0A0A0;
}

.shipping-text {
  color: #A0A0A0;
}

/* BUTTON STATES */

.btn-primary:not(:disabled):not(.disabled):active {
  background: #343A40;
  border: 1px black solid;
  box-shadow: none;
}

.btn-primary:not(:disabled):not(.disabled):focus{
  box-shadow: none;
}

/* CART STYLING */

#itemsInCart {
  background-color: #6394F8;
  border-radius: 10px;
  color: white;
  display: none;
  font-size: 12px;
  line-height: 1;
  padding: 3px 7px;
  text-align: center;
  vertical-align: middle;
  white-space: nowrap;
}
// This is the JavaScript file of my project. This file is responsible for a
// few processes. Namely: Setting up all of the JSON data for the store, populating
// the shop page with the added product data, generating the shop page product cards,
// facilitating the adding of cart data to an array so that it can be used on the
// cart page and for alerting the user on updates and changes to their cart.

// This object, catalogJSON, stores all of the product data related to the store
// including id, title, description, image URL and price.

const catalogJSON = {
  products: [
    {
      id: '00001',
      title: 'St. Helen Chair',
      description: `Sed portitor lectus nibh. Curabitur aliquet quam id dui posuere blandit. Lorem ipsumo dolor sit amet, consictetur adipiscing elit.`,
      imgUrl: 'https://source.unsplash.com/9489sFfgk4c/1000x1000',
      price: 1999,
      readMore: 'st-helen-chair.html'
    },
    {
      id: '00002',
      title: 'Crane Neck Lamp',
      description: `Sed portitor lectus nibh. Curabitur aliquet quam id dui posuere blandit. Lorem ipsumo dolor sit amet, consictetur adipiscing elit.`,
      imgUrl: 'https://source.unsplash.com/0kjNpxQ6dPQ/1000x1000',
      price: 499,
      readMore: 'crane-neck-lamp.html'
    },
    {
      id: '00003',
      title: 'His &amp; Hers Mugs',
      description: `Sed portitor lectus nibh. Curabitur aliquet quam id dui posuere blandit. Lorem ipsumo dolor sit amet, consictetur adipiscing elit.`,
      imgUrl: 'https://source.unsplash.com/qVg2lhK4sVY/1000x1000',
      price: 249,
      readMore: 'his-and-hers-mugs.html'
    },
    {
      id: '00004',
      title: 'Minimalistic Frame',
      description: 'Sed portitor lectus nibh. Curabitur aliquet quam id dui posuere blandit. Lorem ipsumo dolor sit amet, consictetur adipiscing elit.',
      imgUrl: 'https://source.unsplash.com/XwdSGEiOahM/1000x1000',
      price: 659,
      readMore: 'minimalistic-frame.html'
    },
    {
      id: '00005',
      title: 'City Cruiser',
      description: 'Sed portitor lectus nibh. Curabitur aliquet quam id dui posuere blandit. Lorem ipsumo dolor sit amet, consictetur adipiscing elit.',
      imgUrl: 'https://source.unsplash.com/igKjieyjcko/1000x1000',
      price: 8999,
      readMore: 'city-cruiser.html'
    }
  ]
};

// The Product class allows us to construct each one of our products and parse
// the unique values of each to it. Essentially, at this stage, we are describing
// what a product will look like in terms of its characteristics.

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;
  }

// Responsible for converting each JSON field to a string

  toString(){
    return `${this.title} (${this.id}: ${this.description} - R${this.price}`;
  }

// Using toHTML to create a template of the card layout that I would like to use
// 'template' is a string literal which means that I am able to embed expressions
// inside it (Like title, imgUrl, price, description and id).

  toHTML(){
    const template = `<div class="col col-12 col-sm-12 col-md-6 col-lg-4 pt-5 product-container">
        <div class="card text-white bg-dark">
          <img class="card-img-top img-fluid" src="${this.imgUrl}" alt="Image of ${this.title}">
          <div class="card-body">
            <h4 class="card-title">${this.title}</h4>
            <p class="card-subtitle text-muted">R${this.price}.00</p>
            <p class="card-text">${this.description}</p>
            <a href="${this.readMore}" class="btn btn-outline-light">Read More</a>
            <a href="#" data-product-id='${this.id}' class="atc-button btn btn-primary float-right">Add to Cart</a>
          </div>
        </div>
      </div>`;

// David Walsh's blog has a great post about using createRange and createContextualFragment
// to inject a templated string into your HTML without having to do any DOM hacking.
// Post here: https://davidwalsh.name/convert-html-stings-dom-nodes

      const domEl = document.createRange().createContextualFragment(template);
      domEl.querySelector('.atc-button').addEventListener('click', (evt) => console.log(evt.target.getAttribute(`data-product-id`)));

      return domEl;
  }
}

/* The Catalog class sets up the catalog that we need in order to present each
of the products that we have used the above template the firstly populate and then
build */

class Catalog {
  constructor(){
    this.catalog = [];
  }

  add(product) {
    const existingProduct = this.catalog.filter(item => item.id == product.id);

    if(existingProduct.length === 0){
      this.catalog.push(product);
    }
    return this;
  }

  remove(productId) {
    this.catalog = this.catalog.filter(item => item.id !== productId);
    return this;
  }

  findById(productId) {
    return this.catalog.filter(item => item.id===productId)[0];
  }
}

const catalogElement = document.querySelector('.product-container');
const catalog = new Catalog();
catalogJSON.products.forEach(product => {
  catalog.add(new Product(product));
});
catalog.catalog.forEach(product => {
  catalogElement.appendChild(product.toHTML());

})

// console.log(catalog);

/* cartItems is the array where all cart data will be added and stored. So, if a
user clicks on a button to add a product to their cart, the product will be added
to the cartItems array for me to reference later */

let cartItems = [];

// addToCartBtns will select all of the add to cart buttons on the shop page

const addToCartBtns = [...document.querySelectorAll(".atc-button")];

/* A forEach function will ensure that the same function runs on each button once
it is clicked (The product gets added to the cartItems array. */

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
    });
    // alert(${this.title} + " was added to your cart. Your new total is R" + ${this.price});
  });
});
console.log(cartItems);

我希望该数组显示在购物车页面上。

0 个答案:

没有答案