【发布时间】:2020-04-27 11:24:57
【问题描述】:
下面是我的代码。我假设问题来自我的函数,可能涉及一个数字值应该是的字符串或类似的东西。在这方面很新,所以我不能完全确定在点击计算后究竟是什么导致了 NaN 响应。感谢您的帮助。
console.log("Connected")
function calculateTip() {
var billAmt = document.getElementById("price")
var service = document.getElementById("service")
var tip = document.getElementById("tip")
var numOfPpl = document.getElementById("numOfPpl")
// validate input
if (billAmt === "" || service === 0) {
alert("please enter values");
return;
}
//check to see if this input is empty or less than or equal to 1
if (numOfPpl === "" || numOfPpl <= 1) {
numOfPpl = 1;
document.getElementById("each").style.display = "none";
} else {
document.getElementById("each").style.display = "block";
}
// calculate tip
var total = (billAmt * service) / numOfPpl;
total = Math.round(total * 100) / 100;
//next line allows us to always have two digits after a decimal point
total = total.toFixed(2);
//Display the tipdocument.getElementById("")
document.getElementById("totalTip").style.display = "block"
tip.innerHTML = total;
}
//hide tip amoiunt on load
document.getElementById("totalTip").style.display = "none"
document.getElementById("each").style.display = "none"
// click to call funciton
document.getElementById("calculate").onclick = function() {
calculateTip();
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>tip calculator</title>
</head>
<body>
<div class="container">
<h1>Tip calculator</h1>
<form>
<p id="quesiton">How much was your bill?</p>
$ <input type="text" id="price" placeholder="Bill Amount">
<p id="question">How was your service?</p>
<select id="service">
<option disabled selected value="0">Choose an Option</option>
<option value="0.3">30% - Outstanding</option>
<option value="0.2">20% - Good </option>
<option value="0.15">15% - OK</option>
<option value=".05">5% - Poor</option>
</select>
</form>
<p>How many people are sharing the bill</p>
<input id="numOfPpl" type="text" placeholder="Number of People" /> people
<button type="button" id="calculate">Calculate!</button>
</div>
<div id="totalTip">
<sup>$</sup><span id="tip">0.00</span>
<small id="each">each</small>
</div>
</body>
</html>
【问题讨论】:
-
document.getElementById("price")获取一个元素,而不是它的值。你不能用一个元素做数学。 -
像
var numOfPpl = document.getElementById("numOfPpl")这样的语句返回一个实际的 DOM 元素,而不是元素的值。您需要调用.value来获取实际值。要记住的一件事是值将始终是一个字符串,因此如果您要比较数字,则需要通过+运算符、parseInt/parseFloat或Number()
标签: javascript html