javascript - 每次使用 onClick 事件时如何防止变量返回原始值
问题描述
您好我有以下用于 ATM 取款机的 HTML 和 javascript 代码。代码有效,但每次从用户提款后余额不会减少(从 400 美元开始)。我找不到问题所在或如何解决此问题。任何帮助,将不胜感激。
<!DOCTYPE html>
<html>
<head>
<title>ATM</title>
<style>
#bank {
text-align: center;
}
button {
padding-left: 6px;
padding-right: 6px;
}
</style>
<script type="text/javascript" src="Q2.js">
</script>
</head>
<body>
<form id="bank">
<h2> Question 2 </h2>
<h5>ATM Machine</h5>
<input type="text" id="cash" placeholder="Enter withdrawal amount" size="25">
<button type="submit" onclick="validateAmount()" id="button">Submit</button>
</form>
</body>
</html>
这是javascript
balance = 400.00;
function validateAmount() {
a = document.getElementById("cash");
amount = a.value;
if (isNaN(amount)) {
alert("Please enter a numeric value");
} else {
withdrawlAmount();
}
}
function withdrawlAmount() {
if (amount >= balance)
alert("Insufficent Funds");
else if (amount % 20 != 0)
alert("Incorrect withdrawl amount");
else if (amount < balance) {
alert("Succeful transaction\nCurrent Balance: " + (balance - amount) + "$");
balance -= amount;
} else {
return;
}
}
解决方案
您的 HTML 提交按钮将在您每次按下它时刷新页面,从而重新运行您的 javascript 并将余额重置为 400。要解决此问题,请将按钮类型从“提交”更改为“按钮”。
推荐阅读
- javascript - 处理我从异步函数中得到的数据
- javascript - 在渐近循环中找到迭代次数的数学方程?
- javascript - httpParams 删除未定义的参数
- go - 在 for 循环中写入通道会跳过迭代
- python - await 以什么顺序(如果有)执行任务?
- design-patterns - 我不应该注入什么样的依赖项?
- javascript - 有人可以解释一下为什么 for, while, do-while 语句的语法定义标题中的条件部分是“表达式”
- mysql - MySQL SELECT query with many joins takes too long
- three.js - 如何用三种材料替换框架中的模型材料?
- python-3.x - How to sum up column with ValueError: invalid literal for int() with base 10