繁体   English   中英

javascript 101:营业税计算器不响应数据输入

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

我猜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);
    }

真正固定的小提琴

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM