有关在Javascript中添加变量的问题

时间:2014-10-14 12:18:59

标签: javascript

最近开始研究Javascript,并且遇到了将两个变量加在一起的问题

function btn_click()
{
    var money = parseInt(document.getElementById("money").value);
    var dollar = parseInt(3.67 * money);
    var xfer = parseInt(0);
    var total = parseFloat(dollar + xfer);
    var dollar = dollar.toFixed(2);
    if (isNaN(money))
    {
        alert("Please enter a valid amount!");
    }
    else
{
    if (money > 15000)
    {
    xfer = 0;
    document.writeln("Amount in dirhams: " + dollar +" AED<br>");
    document.writeln("Transfer charges: " + xfer +" AED<br>");
    document.writeln("Total: <span style='font-weight:bold'>" +total+" AED<br>");
    }
    else
    {
    xfer = 25;
    document.writeln("Amount in dirhams: " + dollar +" AED<br>");
    document.writeln("Transfer charges: " + xfer +" AED<br>");
    document.writeln("<span style='font-weight:bold'> Total: "+ total + " AED<br></span>");
    }
}

}
基本上,我在&#34; ELSE&#34;部分

document.writeln("Total: <span style='font-weight:bold'>" +total+" AED<br>");

不起作用,当我点击我的按钮时,所有内容都会被计算但是最后一行,最后一行只会显示我的变量&#34; dollar&#34;。让我们说例如我输入100并点击按钮,我的第一行将是367.00 AED而我的第二行将是25 AED但是我的最后一行会说367 AED,它没有总和前两行。

很抱歉,如果我似乎不清楚,如果您需要更多信息,我很乐意给它

谢谢你们

2 个答案:

答案 0 :(得分:1)

您的问题出现在脚本的第一行:

var total = parseFloat(dollar + xfer);

您在total具有有意义的值之前计算xfer 您需要在total行之前计算document.writeln("Total: ...

答案 1 :(得分:-2)

这是因为您只为总数分配了美元价值。你在宣布总数时所做的是:

var total = parseFloat(parseInt(3.67*money) + parseInt(0)) => parseFloat(3.67*money) //because xfer is 0 at that point

所以你需要做的是在给xfer赋值之后计算总数:

function btn_click()
{
    var money = parseInt(document.getElementById("money").value);
    var dollar = parseInt(3.67 * money);
    var xfer = parseInt(0);
    var total = 0;
    var dollar = dollar.toFixed(2);
    if (isNaN(money))
    {
        alert("Please enter a valid amount!");
    }
    else
    {
        if (money > 15000)
        {
            xfer = 0;
            document.writeln("Amount in dirhams: " + dollar +" AED<br>");
            document.writeln("Transfer charges: " + xfer +" AED<br>");
            total = parseFloat(Number(dollar) + Number(xfer));
            document.writeln("Total: <span style='font-weight:bold'>" +total+" AED<br>");
        }
        else
        {
            xfer = 25;
            document.writeln("Amount in dirhams: " + dollar +" AED<br>");
            document.writeln("Transfer charges: " + xfer +" AED<br>");
            total = parseFloat(Number(dollar) + Number(xfer));
            document.writeln("<span style='font-weight:bold'> Total: "+ total + " AED<br></span>");
        }
    }

}