首页 > 解决方案 > 多个带有数字的变量并将结果再次添加到变量中返回错误的结果

问题描述

function calculateAmount(val) {
  var price = val;
  if (quantity >= 100 && quantity < 1000) {
    var divobj = document.getElementById('discount');
    divobj.value = 20;
    var divobj1 = document.getElementById('total');
    var total = ((20 / 100) * parseInt(price)) + parseInt(price);
    divobj1.value = total;
  }
}

例如,如果输入数量为 100,则输出返回为 10020 而不是 100+20 = 120

标签: javascript

解决方案


var price = val;

因为 val 是一个字符串:

var price = +val;

请测试此代码,我希望此代码有效

divobj.value = 20;

请删除上面的行代码:

var total = ((divobj.value / 100) * parseInt(price)) + parseInt(price);

并使用上面的代码而不是下面的代码:

var total = ((20 / 100) * parseInt(price)) + parseInt(price);

推荐阅读