我最近开始学习JS,在做我的第一个项目时遇到了问题。控制台显示未定义变量billAm
。我不确定为什么已经定义了变量,为什么会这样?
下面的代码段:
function calculateTip() {
let billAm = document.getElementById("billam").value;
let serviceQual = document.getElementById("quality").value;
}
if (billAm === "" || serviceQual == 0) {
alert("Please enter values");
}
let total = (billAm * serviceQual);
total = Math.round(total * 100) / 100;
total = total.toFixed(2);
document.getElementById("total").style.display = "block";
document.getElementById("tip").innerHTML = total;
document.getElementById("total").style.display = "none";
document.getElementById("calculate").onclick = function() {
calculateTip();
};
<div id="background">
<h3 class="headline">
Tip calculator
</h3>
<input type=text id="billam" placeholder="Amount">
<h3 class="review">
How was your service?
</h3>
<select id="quality">
<option disabled selected value="0">How was Your Experience?</option>
<option value="0.3">30% - Outstanding</option>
<option value="0.2">20% - Good</option>
<option value="0.15">15% - It was OK</option>
<option value="0.1">10% - Bad</option>
<option value="0.05">5% - Terrible</option>
</select>
<button type="button" id="calculate">Calculate!</button>
<div id="total">
<sup>€</sup><span id="tip">0.00</span>
<script src="script.js"></script>
</div>
</div>
答案 0 :(得分:2)
因为您已经在函数内部定义了它,所以它的范围仅限于该函数。
您可以参考此答案以获取更多详细信息 https://stackoverflow.com/a/500459/1588446