所得税计算器的未定义输出。 JavaScript的

时间:2018-02-09 22:01:18

标签: javascript html nested-if

这是Murach的Javascript和Jquery书中的练习。所得税计算器。代码非常自我解释。错误:未定义正在弹出欠税的价值所在的位置。注释掉if语句输出相同的'undefined'错误。文档说,未定义通常是在未分配或返回变量时输出的,我已经完成了所有这些。

JS

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

   var income;
   var taxOwed;
   var calculateTax = function(income){
    /*if (income > 0 && income < 9275){
        //incomeTax = taxableIncome - 0;
        //percentIT = incomeTax * (10/100);
        taxOwed = (income - 0) * (10/100) + 0;
        taxOwed = parseFloat(taxOwed);
        taxOwed = taxOwed.toFixed(2); //the tax should be rounded two 
        return taxOwed;
    }*/

    if (income < 9275){
        taxOwed = income - 0 * .10 + 0;
    }else if(income > 9275){
        taxOwed = ((income - 9275) * .15) + 927.50;
    }
    return taxOwed;

};

var processEntry = function(){
    income = parseInt($("income").value); //users entry should be converted 
    if(isNaN(income)){
        alert("Entry must be a number");
    }else if (income <= 0){
        alert("income must be greater than 0");
    }else{
        $("taxOwed").value = calculateTax(income);
    }
};  

window.onload = function () {
    $("calculate").onclick = processEntry;
    $("income").focus();
};

HTML

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Ace</title>
    <link rel="stylesheet" href="styles.css">
</head>

<body>
    <h1>Income Tax Calculator</h1>

    <label>Enter taxable income:</label>
    <input type="text" id="income" /> <!--income is variable name for taxable income-->
    <input type="button" value="Calculate" name="calculate" id="calculate" /><br><br>

    <label>Income tax owed:</label>
    <input type="text" id="taxOwed"><br> <!--tax is variable name for taxOwed*-->
<script src="calculate_tax.js"></script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

你可能没有传递任何东西。在收入后放一个调试器语句并打开你的开发控制台,检查变量是否真的有值。

//use val() not value
income = parseInt($("income").val());
debugger;