简体   繁体   English

函数计算折扣两次

[英]Function calculates discount twice

For the life of me I can't seem to figure out why this function won't calculate correctly. 对于我的一生,我似乎无法弄清楚为什么此函数无法正确计算。 If I run this function the discount ( totalPrice ) is applied twice, for example: 20*1.05 == 21 , but when the function runs and it gives me 22.05 . 如果我运行此函数,折扣( totalPrice )将被应用两次,例如: 20*1.05 == 21 ,但是当函数运行时,它会给我22.05

What am I doing wrong? 我究竟做错了什么? Thanks for the help. 谢谢您的帮助。

<script type="text/javascript">
    function codeDiscount() {
        var totalCost = document.getElementById('total').value;
        var custCode = document.getElementById('coupon').value; 

        if (custCode == "ABCD" || custCode == "EFGH")
        {
            totalCost = document.getElementById('total').value; 
            var totalPrice = parseInt(totalCost) * 1.05;
            document.getElementById('total').value = totalPrice;
        }
    }
</script>

I suspect that the problem isn't in this code block. 我怀疑问题不在此代码块中。 Is there anything that would cause codeDiscount() to be called a second time? 有什么会导致第二次调用codeDiscount()的吗?

I suspect there is something wrong with ur code: 我怀疑您的代码有问题:

 <script type="text/javascript">
    function codeDiscount() {
        var totalCost = document.getElementById('total').value;
        var custCode = document.getElementById('coupon').value; 

        if (custCode == "ABCD" || custCode == "EFGH")
        {
            var totalPrice = parseInt(totalCost) * 1.05;
            document.getElementById('total').value = totalPrice;
        }
    }
</script>

Also, please make sure that you don't call the same function twice. 另外,请确保不要两次调用同一函数。 Otherwise, the result will be incorrect. 否则,结果将不正确。

If your total field is being updated every time something changes, it's better to adopt this: 如果每次更改时总字段都在更新,则最好采用以下方法:

Store the total value in a separate variable: 将总值存储在单独的变量中:

var cartTotal = 0;

Then, whenever the sum of items changes, you update it: 然后,每当项目总数改变时,就对其进行更新:

// calculate sum of all products
cartTotal = 0;
for (var i in all_products) {
    cartTotal += all_procucts[i].price;
}
// calculate discount
codeDiscount();

To recalculate discount you use the cartTotal but you only update the field 要重新计算折扣,请使用cartTotal但您只更新该字段

var totalPrice = cartTotal;

if (custCode == 'ABCD') {
    totalPrice *= 1.05;
}

document.getElementById('total').value = totalPrice;

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

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