如何继续添加JS变量? [英] how to keep adding to JS variable?
问题描述
每次用户在框中输入值时,我都会尝试不断添加到js变量。
I am trying to continuously add to a js variable every time a user enters a value into a box.
到目前为止,如果他们输入'21',警报将会说'你的余额是12英镑',但如果我输入'15',我希望它说你的余额为'27',而是说'15'或者更确切地说是最新的金额。
So far if they enter '21' the alert will say 'your balance is £12' but then if I enter '15' I want it to say your balance is '27' but instead it says '15' or rather just the latest amount.
以下代码:
<form action="" method="get">
<input type="number" value="" id="amountDropped">
<input type="submit" value="Deposit amount" onclick="depositedFunds()">
</form>
var firstAmount = 0;
function depositedFunds(){
var ad = document.getElementById("amountDropped");
firstAmount = +firstAmount + +ad.value;
alert ("Your balance is £" + firstAmount);
};
谢谢
推荐答案
进行更改的功能附加在提交按钮上。
The function which makes the change is attached to a submit button.
当用户点击按钮时:
- JS运行
- 值已更新
- 提醒值
- 表单已提交
- 加载新页面
- 新页面中包含
var firstAmount = 0;
- The JS runs
- The value is updated
- The value is alerted
- The form is submitted
- A new page loads
- The new page has
var firstAmount = 0;
in it
您应该:
- 使用服务器端代码动态设置默认值。请参阅不引人注目的JavaScript 和
- 防止提交按钮的默认行为
使用onclick属性,您需要从事件处理函数返回false:
Using an onclick attribute, you need to return false from the event handler function:
onclick="depositedFunds(); return false;"
现代代码会将问题分开,而不是将事情紧密地联系到触发表单提交的特定方式。
Modern code would separate concerns and not tie things so tightly to a specific means of triggering the form submission.
var firstAmount = 0;
function depositedFunds(e) {
e.preventDefault();
var ad = document.getElementById("amountDropped");
firstAmount = +firstAmount + +ad.value;
alert("Your balance is £" + firstAmount);
};
document.querySelector('form').addEventListener('submit', depositedFunds);
<form method="get">
<input type="number" id="amountDropped">
<input type="submit" value="Deposit amount">
</form>
这篇关于如何继续添加JS变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!