getElementById始终返回null

getElementById始终返回null

我正在尝试构建一个简单的预算计算器,每当我单击“提交”按钮时,都不会发生任何事情。当我尝试在控制台中检查变量值时,即使在输入框中键入了值,它们也显示为空。谁能告诉我我在做什么错?在这里浏览了其他问题之后,我一直找不到与我的问题相关的答案。

<!DOCTYPE html>
<html>

<head>
    <title>Budget Calculator</title>
    <style>
        input {display:block;}
        #clear {float:left;}
        #submit {float:left;}
    </style>
    <script type="text/javascript">
        var kms = document.getElementById("kmTravelled");
        var rent = document.getElementById("rentPerMonth");
        var carCost = document.getElementById("carPayment");
        var costPerTrip = (kms/12.75)*20;
        var total = Math.round((costPerTrip + rent + carCost)*100)/100;

        function calculate()
        {
            document.getElementById("calculator").innerHTML = total;
        }
    </script>
</head>
<body>


    <form id="myForm")>
        Km travelled per day: <input type="number" name="kmTravelled" />
        Rent per month: <input type="number" name="rentPerMonth" />
        Car payment per month: <input type="number" name="carPayment" />
    </form>
    <button id="submit" type="button" onclick="calculate();">
        Submit
    </button>
    <button id="clear" type="clear">
        Clear
    </button>

    <p id = "calculator">
    </p>

    <script>
        calculate();
    </script>

</body>

最佳答案

我建议使用id属性并移动部件以获取函数内部的值,以及获取value属性并将字符串值转换为数字以进行计算。



function calculate() {
    var kms = +document.getElementById("kmTravelled").value;
    var rent = +document.getElementById("rentPerMonth").value;
    var carCost = +document.getElementById("carPayment").value;
    var costPerTrip = (kms / 12.75) * 20;
    var total = Math.round((costPerTrip + rent + carCost) * 100) / 100;

  document.getElementById("calculator").innerHTML = total;
}

input { display: block; }
#clear { float: left; }
#submit { float: left; }

<form id="myForm">
  Km travelled per day: <input type="number" name="kmTravelled" id="kmTravelled"/> Rent per month: <input type="number" name="rentPerMonth" id="rentPerMonth" /> Car payment per month: <input type="number" name="carPayment" id="carPayment" />
</form>
<button id="submit" type="button" onclick="calculate();">Submit</button>
<button id="clear" type="clear">Clear</button>
<p id="calculator"></p>

关于javascript - JavaScript getElementById始终返回null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42319095/

10-10 22:24