如何在JavaScript中的数组中添加多个对象?

时间:2018-12-12 20:58:46

标签: javascript arrays object

每次我点击“添加到购物车按钮”,它都会更新cartarray[]。我想做的是为购物车中的每次点击添加一个新对象,这样我就可以为每个不同的购物车项目添加多个对象。

(function() {
  const cartbtn = document.querySelectorAll(".add_to_cart_button");

  cartbtn.forEach(function(btn) {
    btn.addEventListener("click", function(event) {
      if (event.target.parentElement.classList.contains("add_to_cart_button")) {
        let fullpath = event.target.parentElement.previousElementSibling.children[0].children[0].src;
        const item = {};
        item.img = fullpath;
        let name = event.target.parentElement.previousElementSibling.children[3].children[0].textContent;
        item.name = name;
        let price = event.target.parentElement.previousElementSibling.children[3].children[1].textContent;
        let finalprice = price.slice(1).trim();
        item.price = finalprice;
        const cartarray = [];
        var product = function(name, price, img) {
          this.name = name
          this.price = price
          this.img = img
        };
        cartarray.push(new product(name, finalprice, fullpath));
        console.log(cartarray);

      }
    });
  });
})();
<div class="product-item men">
  <div class="product discount product_filter">
    <div class="product_image">
      <img src="images/product_1.png" alt="">
    </div>
    <div class="favorite favorite_left"></div>
    <div class="product_bubble product_bubble_right product_bubble_red d-flex flex-column align-items-center"><span>-$20</span></div>
    <div class="product_info">
      <h6 id="item-name" class="product_name"><a href="single.html">Fujifilm X100T 16 MP Digital Camera (Silver)</a></h6>
      <div class="product_price">$520.00</div>
    </div>
  </div>
  <div class="red_button add_to_cart_button"><a href="#/">add to cart</a></div>
</div>

2 个答案:

答案 0 :(得分:0)

我留下一个答案而不是发表评论,因为我仍然没有发表评论的声誉。如同事所说,提供HTML代码,我们将能够回答。 我注意到可能是“鱼腥”的东西是这两行代码:

const cartbtn = document.querySelectorAll(".add_to_cart_button"); 
if (event.target.parentElement.classList.contains("add_to_cart_button"))

可能是“。”第一行中的内容,第二行中的内容丢失,这会导致代码无法正常工作。我可能是错的,这只是一个假设,没有看到您的完整代码

答案 1 :(得分:0)

cartarray应该在addEventListener之外声明,以便使购物车中的物品持久存在。

我也建议将产品的创建也放在外面,尽管从技术上讲这不是必需的。

请参见以下示例,其中for循环正在模拟您的按钮点击:

const cartarray = [];
const product = function(name, price, img) {
  return {
    name: name,
    price: price,
    img: img
  }
};

for (let x = 1; x < 6; x++) {
  cartarray.push(new product('p' + x, x + '.00', 'path/to/img' + x + 'png'));  
}


console.log(cartarray);