作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试制作一个基本的钱包程序,将我的当前值(value)列在顶部。无论在表格中输入什么数字,然后都会提交,希望然后将总数重新调整为新的金额。相当简单,我觉得我很接近,但我就是不知道缺少什么。
它似乎没有从第一个输入中获取数据并通过函数运行它,也许我需要一个 Action ?我已经尝试过行动,甚至使用新的 currentCash 但它不起作用......真的可以使用一些帮助。非常感谢!
<html>
<head>
<title>My Wallet</title>
<script type="text/javascript">
currentCash = 40000;
function deductFromTotal(){
var spent = document.getElementById("money_spent");
currentCash -= spent;
return currentCash; }
</script>
</head>
<body>
<h2>Current total is: <script type="text/javascript">
document.write(currentCash);
</script> </h2>
<input type="amount" size= 25 Placeholder="How much did you spend today?" ID="money_spent" >
<input type="button" value= "confirm" onClick="deductFromTotal()">
</body>
</html>
最佳答案
I have modified your question and tried to solve your issue.Hope it helps
You were not taking the input's value
You are using document.write ,you should select the element and change the text content
- You should use let ,var or const statements to declare your variables (A good practice to adopt)
let currentCash = 40000;
function deductFromTotal() {
var spent = document.getElementById("money_spent").value;
// check if the entered value is number
if (isNaN(Number(spent))) {
console.log("Numbers only")
} else {
//currentCash = currentCash - spent;
currentCash -= spent;
// give your h2 an id and then use getElementById ,better
document.querySelector("h2").textContent = `Current total is:${currentCash}`;
}
}
// deductFromTotal();
<html>
<head>
<title>My Wallet</title>
</head>
<body>
<input type="amount" size=2 5 Placeholder="How much did you spend today?" id="money_spent">
<input type="button" value="confirm" onClick="deductFromTotal()">
<h2>Current total is:
</h2>
</body>
</html>
关于javascript - 如何在 HTML 中使用 INPUT 中的数据并将其应用于 Javascript 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56684835/
我是一名优秀的程序员,十分优秀!