为什么 JavaScript 正确计算了我的变量,但在 HTML 中显示为未定义?

Why is JavaScript correctly calculating my variable yet displays it as undefined in the HTML?

如何让它显示数字,而不是未定义的数字?

这是一款打赏应用。用户在 #price 中输入他们购买的任何东西(披萨、理发等)的价格,然后 calcTip() 计算小费,将其发送到 calcTotal() 计算总数,并将其发送到 displayAmounts().

我不知道到底发生了什么,但有些东西弄乱了变量 tipcalcTip() 正常工作并成功计算小费金额。我知道这是因为 JavaScript 控制台在我输入 tip; 时显示金额。但是,在页面上,#tipSpan 将提示显示为未定义。

最让我困惑的是变量 total 工作得很好。

有谁知道可能发生了什么或者我该如何解决它?

这里是 HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Tipping App</title>
    <style>
        <!-- Temporary -->
        #error {
            display: none;
        }
    </style>
</head>

<body>
    <div id="wrapper">
        <header>
            <h1>Tipping App</h1>
        </header>

        <section>
            <div class="price">
                <h2>Price Information</h2>
                <label for="priceInput">Enter the price below!</label><input id="priceInput" type="text"><button id="calcButton">Calculate the Tip</button>
                <p id="error">Error: You need to enter the cost!<br><br>Use only numbers and decimal points, no currency symbols or letters.</p>
            </div>

            <div id="tipContainer" class="tip">
                <h2>Tip Information</h2>
                <p id="tipPara">Your tip should be... <span>$<span id="tipSpan"></span></span></p>
            </div>

            <div id="totalContainer" class="total">
                <h2>Total Information</h2>
                <p id="totalPara">Your total is... <span>$<span id="totalSpan"></span></span></p>
            </div>
        </section>
    </div>

<script src="js/app.js"></script>

</body>
</html>

这里是 JavaScript:

///// VARIABLES
//////////////////////////////

var priceInput = document.getElementById("priceInput");
var calcButton = document.getElementById("calcButton");
var error = document.getElementById("error");
var tipContainer = document.getElementById("tipContainer");
var tipPara = document.getElementById("tipPara");
var tipSpan = document.getElementById("tipSpan");
var totalContainer = document.getElementById("totalContainer");
var totalPara = document.getElementById("totalPara");
var totalSpan = document.getElementById("totalSpan");

var tip;
var total;

///// FUNCTIONS
//////////////////////////////

function calcTip() {
    var price = priceInput.value; // This is the price the user inputs
    var minTip = (Math.ceil(price * .15)); // Calculates a 15% tip rounded up to the nearest dollar
    var maxTip = (price * .2); // Calculates a 20% tip

    if (isNaN(price) || price === "") {
        // If the user doesn't enter a number
        // Or doesn't enter anything,
        // Then display the error message
        error.style.display = "block";
        return;
    } else {
        error.style.display = "none";
        if (maxTip < minTip) {
            // If the 20% tip is less than the 15% rounded tip,
            // Then let's go with that 20% tip
            calcTotal(price, maxTip);
            tip = maxTip;
        } else {
            // Otherwise, let's just do the 15%
            calcTotal(price, minTip);
            tip = minTip;
        };
    };
};

function calcTotal(price, tip) {
    // Add the price and the tip together to yield the total
    price = parseInt(price);
    tip = parseInt(tip);
    total = (price + tip);
    displayAmounts();
}

function displayAmounts() {
    // Update the page to display the tip and the total to the user
    tipContainer.style.display = "block";
    totalContainer.style.display = "block";
    tipSpan.innerText = tip;
    totalSpan.innerText = total;
}

///// EVENTS
//////////////////////////////

calcButton.addEventListener("click", calcTip);

另外,无关,但是我的 JavaScript 好看吗?它是干净的代码吗?我希望在不久的将来找到一份网络开发工作,我知道我需要擅长JavaScript。

尝试更改您的方法定义,使其传递以下值:

displayAmounts(); 应该变成 displayAmounts(tip, total);

参见 fiddle here

此外,假设您希望比整数更准确,您应该使用 parseFloat 而不是 parseInt

WORKING DEMO

更新函数参数

function calcTotal(price, maxTip) {
    // Add the price and the tip together to yield the total
    price = parseInt(price);
    tip = parseInt(maxTip);
    total = (price + tip);
    displayAmounts();
}

此处参数 tip 覆盖了全局变量。调用时将其替换为 maxTip

1) 在函数displayAmounts中,传递参数tip & total

2) 而不是

tipSpan.innerText = 小费,

试试

tipSpan.innerHTML = 小费;

总计相同,

使用 totalSpan.innerHTML = 总计

而不是

totalSpan.innerText;

那么应该可以了

只是一个小错误!

而不是:

calcTotal(price, minTip);
tip = minTip;

做:

tip = minTip;
calcTotal(price, minTip);

这种方式的小费是在 displayAmounts 为 运行 之前计算的。

关于您的代码:

刚入门还可以。我建议在 javascript 上浏览 w3school 的 tutorials。 javascript用得越多,效果越好。

如果您想要我推荐的学习路径,请告诉我。

innerText 仅适用于 IE。 textContent 符合 W3C,但如果您希望您的代码符合标准且跨浏览器安全,您应该使用:

while( tipSpan.firstChild ) {
    tipSpan.removeChild( tipSpan.firstChild );
}
tipSpan.appendChild( document.createTextNode(tip) );

也对 totalSpan 执行此操作。