【发布时间】: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