javascript 101:增值税计算器不响应数据输入

javascript 101: sales tax calculator does not respond to data entry

本文关键字:不响应 数据 输入 计算器 增值税 javascript      更新时间:2023-09-26

我猜onload函数没有正确实现。输入数字或字母不会得到适当的错误或计算响应。

这是我目前的代码:

http://jsfiddle.net/907yn57r/

var $ = function (id) {
    return document.getElementById(id);
}
var calculateTaxAndTotals = function () {
    var taxRate = parseFloat($("taxRate").value); //The tax rate, as a percentage (e.g. 8.5)
    var subTotal = parseFloat($("itemPrice").value); //An item price ex $5.95
    $("salesTax").value = "";
    $("totalItemCost").value = "";
    if (isNaN(taxRate) || taxRate <= 0) {
        document.taxCalc.taxRate.focus();
        document.$("taxRateMessage").firstChild.nodeValue = "Please enter a valid value.";
    } else if (isNaN(itemPrice) || itemPrice <= 0) {
        document.$("priceMessage").firstChild.nodeValue = "Please enter a valid value.";
    } else {
        var salesTax = subTotal * (taxRate / 100);
        var totalItemCost = salesTax + itemPrice;
        $("orderTotal").focus();
        alert(totalItemCost);
    }
}
window.onload = function () {
    calculateTaxAndTotals();
}

有几个问题。

首先,JSFiddle处理主html结构本身,因此您不需要新的body标记等。

其次,这里的Javascript需要在头部或主体中加载(在JSFiddle的左上角,您可以选择不同的位置进行加载)。

最后,CalculateTaxAndTotals的定义中有一些错误,应该是

if (isNaN(taxRate) || taxRate <= 0) {
        document.taxCalc.taxRate.focus();
        $("taxRateMessage").firstChild.nodeValue = "Please enter a valid value.";
    } else if (isNaN(subTotal) || itemPrice <= 0) {
        $("priceMessage").firstChild.nodeValue = "Please enter a valid value.";
    } else {
        var salesTax = subTotal * (taxRate / 100);
        var totalItemCost = salesTax + itemPrice;
        $("orderTotal").focus();
        alert(totalItemCost);
    }

真正固定的Fiddle

最后的问题是在itemPrice上调用isNaN,但变量itemPrice不存在。