我会保持简单,在我的jsfiddle中我有一个使用javascript的购物车。我想要的是有人点击按钮,它会将一个项目添加到购物车。不幸的是,该函数不会调用AdditemtoCart,除非它超出了让我疯狂的功能之外。让我知道我做错了什么。
jsfiddle链接:https://jsfiddle.net/w2z3rb9h/51/
<div id="cart" class="glyphicon glyphicon-shopping-cart">
<div id="money">
$</div>
<div id="length">
Items
</div>
</div>
<button name="button" id="addItem">
Add Item
</button>
HTML Code above
// [(START)Cart]-------->
var cart = [];
// [(END)Cart]---------->
// [(START)Factory]-------->
var Item = function(name, price, count) {
this.name = name;
this.price = price;
this.count = count;
};
// [(END)Cart]-------------->
// [(START)Adding Items to Cart]-------->
function addItemToCart(name, price, count){
for (var key in cart) {
if (cart[key].name === name) {
cart[key].count += count;
cart[key].price += price;
return;
}
}
var item = new Item(name, price, count);
cart.push(item);
}
// [(END)Adding Items to Cart]---------->
// [(START)Remove Item From Cart]-------->
function removeItemFromCart(name,price) {
for(var key in cart) {
if(cart[key].name === name) {
cart[key].count --;
cart[key].price -= price;
if(cart[key].count === 0) {
cart.splice(key,1);
}
break;
}
}
}
// [(END)Remove Item From Cart]-------->
// [(START)Remove All Item From Cart]-->
function removeItemFromCartAll(name){
for (var key in cart){
if(cart[key].name === name){
cart.splice(key, 1);
break;
}
}
}
// [(END)Remove All Item From Cart]---->
function call() {
addItemToCart("Apple", 1.2, 1);
alert("It works");
}
document.getElementById("addItem").addEventListener("mousedown", call);
// [(START)Get Cart Amount] ----------->
function cartlength() {
var x = 0;
for (var key in cart) {
x += cart[key].count;
}
document.getElementById("length").innerHTML = "Items:" + x;
}
//Invoked:Get Cart Amount
cartlength();
// [(END)Get Cart Amount] ----------->
// [(START)Price] ------------------->
function cartprice() {
var y = 0;
for (var key in cart) {
y += cart[key].price;
}
document.getElementById("money").innerHTML = "$" + y;
}
//Invoke: Price
cartprice();
// [(END)Price] --------------------->
答案 0 :(得分:0)
当您点击addItem
按钮时,它会调用call
功能,同时也会调用addItemToCart
和alert
内部。您可以测试它在addItemToCart
内添加提醒。项目现在在cart
数组内。您需要更新cart
div,调用cartlength
和cartprice
函数。以这种方式更新call
方法:
function call() {
addItemToCart("Apple", 1.2, 1);
cartlength();
cartprice();
alert("It works");
}