【问题标题】:On click, push one item from an an array to another, and change text dependent on items in array单击时,将一个项目从一个数组推送到另一个,并根据数组中的项目更改文本
【发布时间】:2021-12-26 18:43:41
【问题描述】:

我正在尝试设置它,以便如果我单击“addtocart”类的按钮,它将检查 HTML 文档中按钮的 id 并遍历产品数组对象,直到找到具有与元素上的按钮相同的 ID,然后将其推送到购物车数组。然后,我需要更改“cartamnt”跨度的内部文本,以便根据添加到购物车中的商品数量,文本“0 购物车”变为“1 购物车”等。

//Arrays
var products = [{
    Price: 20,
    Name: "Football Helmet",
    Description: "Titans football helmet",
    Id: "Titan_a"
  },
  {
    Price: 15,
    Name: "Light Blue Shirt",
    Description: "Titans light blue shirt",
    Id: "Titan_b"
  },
  {
    Price: 15,
    Name: "White Shirt",
    Description: "Titans white shirt",
    Id: "Titan_c"
  },
  {
    Price: 15,
    Name: "Blue Shirt",
    Description: "Titans blue shirt",
    Id: "Titan_d"
  },
  {
    Price: 25,
    Name: "Hockey Stick",
    Description: "Titans hockey stick",
    Id: "Titan_d"
  }
];

var cart = [];

//All the button variables
var addtocart = document.getElementsByClassName("add");
var camount = document.getElementById("cartamnt");
cartamnt.innerText = "0 cart"

addtocart.onclick = function(products, cart) {
  for (var i = 0; i < products.length; i++) {
    if (addtocart.Id == products.Id) {
      cart.push(products.Id[i])
      cartamnt.innerText = i++ + "cart"
    }
  }
}
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="css/styles.css">
</head>

<body>
  <h1 id="main_title">Titan Sports and Apparel LLC</h1>
  <div class="main">
    <div class="row">
      <span href="checkout.html" id="cartamnt">0 cart</span>
      <br />
    </div>
    <div class="row">
      <div class="column">
        <h1>Football helmet</h1>
        <img id="img" src="img/Helmet_A.jpg">
        <p>Price: $20</p>
        <p>Official Titan Sportswear Helmet</p>
        <button class="add" id="Titan_a">Add to cart</button>
        <button id="Remove_a">Remove from cart</button>
      </div>
      <div class="column">
        <h1>Light Blue Shirt</h1>
        <img id="img" src="img/Shirt_A.jpg">
        <p>Price: $15</p>
        <p>Light blue cotton material Titans shirt</p>
        <button class="add" id="Titan_b">Add to cart</button>
        <button id="Remove_b">Remove from cart</button>
      </div>
      <div class="column">
        <h1>White Shirt</h1>
        <img id="img" src="img/Shirt_B.jpg">
        <p>Price: $15</p>
        <p>White cotton material Titans shirt</p>
        <button class="add" id="Titan_c">Add to cart</button>
        <button id="Remove_c">Remove from cart</button>
      </div>
      <div class="column">
        <h1>Blue Shirt</h1>
        <img id="img" src="img/Shirt_C.jpg">
        <p>Price: $15</p>
        <p>Blue cotton material Titans shirt</p>
        <button class="add" id="Titan_d">Add to cart</button>
        <button id="Remove_d">Remove from cart</button>
      </div>
      <div class="column">
        <h1>Hockey Stick</h1>
        <img id="img" src="img/Stick_A.png">
        <p>Price: $25</p>
        <p>Black Titans hockey stick</p>
        <button class="add" id="Titan_e">Add to cart</button>
        <button id="Remove_e">Remove from cart</button>
      </div>
    </div>
  </div>
  <a href="index.html">Homepage</a>
  <footer>© Titan Sports and Apparel LLC | Email: TitanSportsApparel@gmail.com</footer>
  <script src="js/shoppingCart.js"></script>
</body>

</html>

【问题讨论】:

    标签: javascript html arrays


    【解决方案1】:

    你的代码有点乱。我稍微清理了它以帮助您入门,但我真的建议您将其发布到Code Review 以了解如何改进它。

    首先要注意的是,您正在使用“添加”按钮的id 来存储产品的ID。这是一个问题有两个原因:

    1. id 属性的目的是为元素提供唯一标识符,而不是存储数据。
    2. 您还有一个“删除”按钮,可以将产品从购物车中删除。使用您的方法,它将具有与“添加”按钮相同的id,这是不正确的,因为id 应该是唯一的。另一种方法是给它一个不同的 id,并在 JS 中以某种方式从中提取产品 id,这确实很复杂。

    这就是为什么我们将使用data attributes 而不是id 来存储产品ID。例如:

    <button class="add" data-product="Titan_a">Add to cart</button>
    <button class="remove" data-product="Titan_a">Remove from cart</button>
    

    现在,您的 JS 的问题在于您的 addtocart 变量实际上是所有按钮的数组,而不是单个按钮,因此您不能只将 onclick 事件附加到它。您需要遍历所有按钮并将onclick 事件单独附加到它们。

    所以我们会得到这样的结果:

    const addButtons = document.getElementsByClassName("add");
    const removeButtons = document.getElementsByClassName("remove");
    
    for (const addButton of addButtons) {
        addButton.addEventListener("click", () => {
             ...
        });
    }
    for (const removeButton of removeButtons) {
        removeButton.addEventListener("click", () => {
             ...
        });
    }
    

    现在很容易实现添加和删除。你不需要手动循环抛出你的数组,你可以简单地使用 find 函数和一些其他有用的“内置”数组函数。

    这是一个完整的工作示例:

    let products = [{
        Price: 20,
        Name: "Football Helmet",
        Description: "Titans football helmet",
        Id: "Titan_a"
      },
      {
        Price: 15,
        Name: "Light Blue Shirt",
        Description: "Titans light blue shirt",
        Id: "Titan_b"
      },
      {
        Price: 15,
        Name: "White Shirt",
        Description: "Titans white shirt",
        Id: "Titan_c"
      },
      {
        Price: 15,
        Name: "Blue Shirt",
        Description: "Titans blue shirt",
        Id: "Titan_d"
      },
      {
        Price: 25,
        Name: "Hockey Stick",
        Description: "Titans hockey stick",
        Id: "Titan_e"
      }
    ];
    
    let cart = [];
    
    const addButtons = document.getElementsByClassName("add");
    const removeButtons = document.getElementsByClassName("remove");
    const amountLabel = document.getElementById("cartamnt");
    
    for (const addButton of addButtons) {
      addButton.addEventListener("click", () => {
        let product = products.find(p => p.Id == addButton.dataset.product);
        cart.push(product);
        amountLabel.innerText = cart.length + "items";
      });
    }
    for (const removeButton of removeButtons) {
      removeButton.addEventListener("click", () => {
        const index = cart.findIndex(p => p.Id === removeButton.dataset.product); // index of product to remove
        cart.splice(index, 1); // removing it
        amountLabel.innerText = cart.length + "items";
      });
    }
    <!DOCTYPE html>
    <html>
    
    <body>
      <h1 id="main_title">Titan Sports and Apparel LLC</h1>
      <div class="main">
        <div class="row">
          <span href="checkout.html" id="cartamnt">0 cart</span>
          <br />
        </div>
        <div class="row">
          <div class="column">
            <h1>Football helmet</h1>
            <img id="img" src="img/Helmet_A.jpg">
            <p>Price: $20</p>
            <p>Official Titan Sportswear Helmet</p>
            <button class="add" data-product="Titan_a">Add to cart</button>
            <button class="remove" data-product="Titan_a">Remove from cart</button>
          </div>
          <div class="column">
            <h1>Light Blue Shirt</h1>
            <img id="img" src="img/Shirt_A.jpg">
            <p>Price: $15</p>
            <p>Light blue cotton material Titans shirt</p>
            <button class="add" data-product="Titan_b">Add to cart</button>
            <button class="remove" data-product="Titan_b">Remove from cart</button>
          </div>
          <div class="column">
            <h1>White Shirt</h1>
            <img id="img" src="img/Shirt_B.jpg">
            <p>Price: $15</p>
            <p>White cotton material Titans shirt</p>
            <button class="add" data-product="Titan_c">Add to cart</button>
            <button class="remove" data-product="Titan_c">Remove from cart</button>
          </div>
          <div class="column">
            <h1>Blue Shirt</h1>
            <img id="img" src="img/Shirt_C.jpg">
            <p>Price: $15</p>
            <p>Blue cotton material Titans shirt</p>
            <button class="add" data-product="Titan_d">Add to cart</button>
            <button class="remove" data-product="Titan_d">Remove from cart</button>
          </div>
          <div class="column">
            <h1>Hockey Stick</h1>
            <img id="img" src="img/Stick_A.png">
            <p>Price: $25</p>
            <p>Black Titans hockey stick</p>
            <button class="add" data-product="Titan_e">Add to cart</button>
            <button class="remove" data-product="Titan_e">Remove from cart</button>
          </div>
        </div>
      </div>
      <a href="index.html">Homepage</a>
      <footer>© Titan Sports and Apparel LLC | Email: TitanSportsApparel@gmail.com</footer>
    </body>
    
    </html>

    【讨论】:

    • 非常感谢您的帮助并向我解释我的代码存在的问题。我不知道 find() 函数,使它更容易。我必须对这段代码做一些其他的事情,如果我将来有问题,我会使用你提供的代码审查链接。 @迈克尔哈达德
    【解决方案2】:

    您只需遍历数组,然后将event listener 添加为:

    addtocart.forEach(btn => {
      btn.addEventListener("click", (e) => {
        const Id = e.target.id;
        const product = products.find(o => o.Id === Id);
        product &&  cart.push({ ...product });
        cartamnt.innerText = cart.length + " cart";
      })
    })
    

    var products = [{
        Price: 20,
        Name: "Football Helmet",
        Description: "Titans football helmet",
        Id: "Titan_a"
      },
      {
        Price: 15,
        Name: "Light Blue Shirt",
        Description: "Titans light blue shirt",
        Id: "Titan_b"
      },
      {
        Price: 15,
        Name: "White Shirt",
        Description: "Titans white shirt",
        Id: "Titan_c"
      },
      {
        Price: 15,
        Name: "Blue Shirt",
        Description: "Titans blue shirt",
        Id: "Titan_d"
      },
      {
        Price: 25,
        Name: "Hockey Stick",
        Description: "Titans hockey stick",
        Id: "Titan_d"
      }
    ];
    
    var cart = [];
    
    //All the button variables
    var addtocart = [...document.getElementsByClassName("add")];
    var camount = document.getElementById("cartamnt");
    cartamnt.innerText = "0 cart"
    
    addtocart.forEach(btn => {
      btn.addEventListener("click", (e) => {
        const Id = e.target.id;
        const product = products.find(o => o.Id === Id);
        product &&  cart.push({ ...product });
        cartamnt.innerText = cart.length + " cart";
      })
    })
    <h1 id="main_title">Titan Sports and Apparel LLC</h1>
    <div class="main">
      <div class="row">
        <span href="checkout.html" id="cartamnt">0 cart</span>
        <br />
      </div>
      <div class="row">
        <div class="column">
          <h1>Football helmet</h1>
          <img id="img" src="img/Helmet_A.jpg">
          <p>Price: $20</p>
          <p>Official Titan Sportswear Helmet</p>
          <button class="add" id="Titan_a">Add to cart</button>
          <button id="Remove_a">Remove from cart</button>
        </div>
        <div class="column">
          <h1>Light Blue Shirt</h1>
          <img id="img" src="img/Shirt_A.jpg">
          <p>Price: $15</p>
          <p>Light blue cotton material Titans shirt</p>
          <button class="add" id="Titan_b">Add to cart</button>
          <button id="Remove_b">Remove from cart</button>
        </div>
        <div class="column">
          <h1>White Shirt</h1>
          <img id="img" src="img/Shirt_B.jpg">
          <p>Price: $15</p>
          <p>White cotton material Titans shirt</p>
          <button class="add" id="Titan_c">Add to cart</button>
          <button id="Remove_c">Remove from cart</button>
        </div>
        <div class="column">
          <h1>Blue Shirt</h1>
          <img id="img" src="img/Shirt_C.jpg">
          <p>Price: $15</p>
          <p>Blue cotton material Titans shirt</p>
          <button class="add" id="Titan_d">Add to cart</button>
          <button id="Remove_d">Remove from cart</button>
        </div>
        <div class="column">
          <h1>Hockey Stick</h1>
          <img id="img" src="img/Stick_A.png">
          <p>Price: $25</p>
          <p>Black Titans hockey stick</p>
          <button class="add" id="Titan_e">Add to cart</button>
          <button id="Remove_e">Remove from cart</button>
        </div>
      </div>
    </div>
    <a href="index.html">Homepage</a>
    <footer>© Titan Sports and Apparel LLC | Email: TitanSportsApparel@gmail.com</footer>

    【讨论】:

      【解决方案3】:

      这又快又脏,但它应该可以完成你的工作:

      请注意,我在“从购物车中删除”按钮上添加了一个“删除”类,并将相同的 id 作为 id 属性(因为我们需要在 products 数组中搜索它们)。这应该可以工作,作为奖励,当您在购物车中有多个相同的产品但只想删除一个时,我添加了一个 if 案例。

      我还附加了不同的事件监听器。

      const addProductToCard = (e) => {
          const productToAdd = products.find(i => i.Id === e.target.id);
          cart.push(productToAdd);
      }
      
      const removeFromCard = (e) => {
          const identical = cart.filter(i => i.Id === e.target.id);
      
          if (identical.length === 1) {
              cart = cart.filter(i => i.Id !== e.target.id);
          } else {
              cart = [...identical.splice(1), ...cart.filter(i => i.Id !== e.target.id)];
          }
      }
      
      document.querySelectorAll('.add').forEach(i => i.addEventListener("click", addProductToCard));
      document.querySelectorAll('.remove').forEach(i => i.addEventListener("click", removeFromCard));
      

      【讨论】:

        猜你喜欢
        • 2016-11-04
        • 2019-05-17
        • 1970-01-01
        • 2017-03-02
        • 2022-06-13
        • 2014-02-04
        • 1970-01-01
        • 2019-01-19
        • 1970-01-01
        相关资源
        最近更新 更多