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

时间:2015-03-05 05:53:56

标签: javascript function dom

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

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

我不确切知道会发生什么,但是变量tip会让人感到困惑。 calcTip()正常工作并成功计算小费金额。我知道这一点,因为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看起来不错吗?这是干净的代码吗?我希望在不久的将来找到一个Web开发工作,我知道我需要擅长JavaScript。

5 个答案:

答案 0 :(得分:0)

尝试更改方法定义,以便传递以下值:

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

查看小提琴here

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

答案 1 :(得分:0)

<强> 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

答案 2 :(得分:0)

1)在功能displayAmounts中,传递参数tip&amp;总计

2)而不是

tipSpan.innerText = tip,

尝试

tipSpan.innerHTML = tip;

和总计相同,

使用totalSpan.innerHTML = total

而不是

totalSpan.innerText;

然后它应该工作

答案 3 :(得分:0)

只是一个小错误!

而不是:

calcTotal(price, minTip);
tip = minTip;

执行:

tip = minTip;
calcTotal(price, minTip);

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

紧靠您的代码:

刚开始时这很好。我建议在javascript上浏览w3school的tutorials。你使用javascript越多,你就会越好。

如果您想要一条学习路径,我建议您参加,请告诉我。

答案 4 :(得分:0)

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

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

也为totalSpan执行此操作。