简体   繁体   English

在淘汰赛购物车中创建总成本函数

[英]Creating total cost function in Knockout shopping cart

I am very new to js knockout and have been tasked with adding functionality to a shopping cart. 我对JS淘汰赛非常陌生,并且受过向购物车添加功能的任务。 I have created a function for the total cost of the items in the cart but it doesn't work (code is highlighted below). 我已经创建了一个用于购物车中物品总费用的函数,但是它不起作用(代码在下面突出显示)。

My question is: how do I change this function, or create a new one, that outputs the total cost of the items in the cart, and that changes if an item is removed or the quantity of an item is changed? 我的问题是:如何更改此功能或创建一个新功能,以输出购物车中物品的总成本,并且如果移除某物品或更改一件物品的数量,该功能也会改变?

Here's the code and a brief explanation of the cart: 这是购物车的代码和简要说明:

http://jsfiddle.net/b4atrw2g/5/ http://jsfiddle.net/b4atrw2g/5/

The cart has two main sections. 该购物车有两个主要部分。 In the 'Add New Item' section, the user enters the name, cost and quantity of the item, then clicks 'Add Item'. 在“添加新项目”部分,用户输入该项目的名称,成本和数量,然后单击“添加项目”。

The item then appears in the 'Items in Cart' section with the cost and quantity. 然后,该项目连同成本和数量一起显示在“购物车中的项目”部分。 The user is still able to change the quantity of the item when it's in the cart. 当商品在购物车中时,用户仍然可以更改其数量。

I've created a function called 'getTotalCost', but that outputs the total cost of the item before it is added to the cart, and disappears once the item is added to the cart. 我创建了一个名为“ getTotalCost”的函数,但是该函数在将商品添加到购物车之前输出该商品的总费用,并且在将该商品添加到购物车后消失。

Here's the function: 功能如下:

 viewModel.getTotalCost = ko.pureComputed(function() { var total = 0; total += viewModel.newItemPrice() * viewModel.newItemQuantity(); return total; }, viewModel); 

Thank you in advance. 先感谢您。

viewModel.getTotalCost = ko.pureComputed(function() 
{
    var total = 0;
    arr = viewModel.itemsInCart();
    for (i = 0; i< arr.length;i++)
       total += arr[i].price * arr[i].quantity;
    return total; 
}

http://jsfiddle.net/b4atrw2g/6/ http://jsfiddle.net/b4atrw2g/6/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM