0

我正在编写一个简单的购物车来处理用户输入,然后再将金额转交给我的支付处理器。我有有效的代码,但我不确定它是否是计算总数的最有效方法。其次,我想在选择三个类别时添加百分比折扣的可能性。我最初有一种方法可以对 IF 语句进行大量检查,但效率低下,并且还有一个未解决的问题。我将如何对我预先存在的代码应用百分比折扣(如果四个项目类别中的三个> 0)?

  var subtotal = 0;
  var veu4 = 0;
  var veo4 = 0;
  var vres = 0;
  var vcvl = 0;
  var vedb = 0;

  function update_price(pin) {
  quantity = parseFloat(pin.value);

  var callname = pin.name;

    if (callname == "item1"){
      price = quantity * 50;
      subtotal -= vcvl * 50;
      vcvl = quantity;
    }
    else if (callname == "item2"){
      price = quantity * 50;
      subtotal -= vres * 50;
      vres = quantity;
    }
    else if (callname == "item3"){
      price = quantity * 99;
      subtotal -= veu4 * 99;
      veu4 = quantity;
    }
    else if (callname == "item4"){
      price = quantity * 129;
      subtotal -= veo4 * 129;
      veo4 = quantity;
    }
    else{
      //commented out irrelevant
    }


 subtotal += price;
 passtotal = document.getElementById("ftotal"); 
 total = document.getElementById("ptotal");
 total.innerHTML = subtotal;
 passtotal.value = subtotal;
 passtotal.innerHTML = subtotal;   
}

}

非常感谢您的帮助!

4

1 回答 1

1

有很多方法可以做到这一点,但这会更干燥一些。

var items = {
  item1: 50,
  item2: 50,
  item3: 99,
  item4: 129
};

var cart = {};

function update_price(pin) {
  quantity = parseFloat(pin.value);

  var callname = pin.name;

  // Get the total for this item with quantity
  price = quantity * items[callname];

  // Update quantity in cart
  cart[callname] = {quantity: quantity, subtotal: price};  

  passtotal = document.getElementById("ftotal"); 
  total = document.getElementById("ptotal");
  total.innerHTML = price;
  passtotal.value = price;
  passtotal.innerHTML = price;
}

我认为您对总计/小计的概念很奇怪。看起来您的总计/小计将始终等于您上次计算的价格 * 数量。也许您生成的代码是错误的。因此,我的也会略有错误。要修复它,使总数等于购物车中的所有小计。

至于将这些数据传递给您的服务器,您应该传递将要购买的物品和数量。在服务器端,应重新计算小计和总计。我添加了您的购物车变量来帮助解决这个问题。只需序列化这些数据并将其发送到您的服务器处理。 实际向用户收费时,不要以 ftotal 或 ptotal 的值准确。

于 2012-10-23T19:12:43.600 回答