为什么if语句在其他情况下执行?

时间:2014-09-28 23:49:57

标签: javascript if-statement

我一直试图解决这个问题。出于某种原因,

下的第一个if语句

否则if(customerType =" T")

即使customerType不等于" T"仍然执行,因此,无论输入是什么,discountPercent都会变为.40,除非customerType等于" R",&# 34; C"或" T"。任何人都可以帮助我吗?

var $ = function (id) {
return document.getElementById(id);
}

var calculate_click = function () {
var customerType = $("type").value.toUpperCase;
var invoiceSubtotal = parseFloat( $("subtotal").value );
$("subtotal").value = invoiceSubtotal.toFixed(2);
var discountPercent = .0;
var valid = false;

if (customerType == "R") {
    valid = true;
    if (invoiceSubtotal < 100){
        discountPercent = .0;
    }
    else if (invoiceSubtotal >= 100 && invoiceSubtotal < 250){
        discountPercent = .1;
    }
    else if (invoiceSubtotal >= 250 && invoiceSubtotal < 500){
        discountPercent = .25;
    }
    else if (invoiceSubtotal >= 500){
        discountPercent = .30;
    }
}

else if (customerType == "C") {
    valid = true;
    discountPercent = .20;
    }

else if (customerType = "T"){
    valid = true;
    if(invoiceSubtotal < 500){
        discountPercent = .40;
    }
    if(invoiceSubtotal >= 500){
        discountPercent = .50;
    }
}

else if(!valid){
    discountPercent = .10;
}

var discountAmount = invoiceSubtotal * discountPercent;
var invoiceTotal = invoiceSubtotal - discountAmount;

$("percent").value = (discountPercent * 100).toFixed(2) ;
$("discount").value = discountAmount.toFixed(2);
$("total").value = invoiceTotal.toFixed(2);

$("type").focus;
}

2 个答案:

答案 0 :(得分:1)

else if (customerType = 'T')始终评估为true,因为它没有比较任何内容,而是将'T'值分配给customerType。

也许你想做else if (customerType == 'T')

答案 1 :(得分:1)

你可能意味着:

else if (customerType == "T")
                      ^
                typo here corrected

由于

else if (customerType = "T")

与:

完全相同
else if ("T")

“T”正在评估为真,无论如何,这句话总是正确的。