如何计算总价格JS

时间:2017-08-22 19:42:30

标签: javascript

我有这段代码:

function calculate_sale_article(id){
  var article_price = $("#article_price_"+id).val()
  var article_cant = $("#article_cant_"+id).val()
  var article_discount = $("#article_discount_"+id).val()

  $("#article_ammount").val(article_price * article_cant / article_discount)
}
  

错误:“无限”

article_discount0到达时出现此错误,我该如何解决此问题?

2 个答案:

答案 0 :(得分:0)

添加一个简单的零检查(除以零的异常处理)。替换以下行:

$("#article_ammount").val(article_price * article_cant / article_discount)

有这样的事情:

if (article_discount != 0)
  $("#article_ammount").val(article_price * article_cant / article_discount)
else
  $("#article_ammount").val(article_price * article_cant)

答案 1 :(得分:0)

    var article_price = parseInt($("#article_price_"+id).val());
      var article_cant = parseInt($("#article_cant_"+id).val());
 var discount = parseInt($("#article_discount_"+id).val());
      var article_discount = discount?discount:1;

      $("#article_ammount").val(article_price * article_cant / article_discount)