多种计算方式,价格不同

时间:2014-04-02 12:53:22

标签: javascript jquery

我制作了一个小脚本来计算订单上的数字和价格。 我怎么需要一些帮助来弄清楚如何计算不同对象的不同价格和eatch对象的数量

我的脚本现在看起来像这样

 function calculateSum() {
  var antal = 0;
  var sub = 0;
  var price = 30;
  $(".mad" && ".mad2").each(function() {
  //add only if the value is number
  if (!isNaN(this.value) && this.value.length != 0) {
  antal += parseFloat(this.value);
  sub = antal * price;
  $(this).css("background-color", "#ffffff");
  }
  else if (this.value.length != 0){
  $(this).css("background-color", "#e68d8d");
  }
  });
  $("#antalrug").html(antal.toFixed(0));
  $("#subtotal").html(sub.toFixed(0));
 }

到目前为止,所以上帝,但我需要价格灵活,以便如果它的" .mad"它的30,如果它的.mad2它的35! 我如何设置它以便计算取决于函数正在查看的女巫类?

像:

if (this = "mad2") {
      price = 35; 
  }
else {
      price = 30;
      $(

我简直无法让它工作我已经尝试了两种消化方法 我的脚本现在看起来像这样

    $(".mad, .mad2, .mad3, .mad4, .mad5, .mad6").each(function() {
        //add only if the value is number
        if (this.value.trim().length != 0 && !isNaN(this.value.trim()) ) {
        //Set max to 25
        if (this.value >= 25){
        this.value= 25
        }
        if($(this).hasClass("mad2")){
            price = 35;
            }
        else{
            price = 30;
            }
            antal += parseFloat(this.value);
            subtotal = antal*price;
            $(this).css("background-color", "#ffffff");
        }
        else if (this.value.length != 0){
             $(this).css("background-color", "#e89898");
        }
    });
现在所有的价格都是35?

2 个答案:

答案 0 :(得分:1)

每个函数内部

if ($(this).is('.mad')) {
    price = 30;
} else {
    price = 35;
}

答案 1 :(得分:0)

为什么不给选择器.mad1和mad2一个额外的类,然后你可以这样做:

$(".newClass").each(function() {

    if($(this).hasClass("mad1")){
        price = 30;
    }
    else{
        price = 35;
    }
}
相关问题