如何继续添加JS变量? [英] how to keep adding to JS variable?

查看:251
本文介绍了如何继续添加JS变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次用户在框中输入值时,我都会尝试不断添加到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.

当用户点击按钮时:


  1. JS运行

  2. 值已更新

  3. 提醒值

  4. 表单已提交

  5. 加载新页面

  6. 新页面中包含 var firstAmount = 0;

  1. The JS runs
  2. The value is updated
  3. The value is alerted
  4. The form is submitted
  5. A new page loads
  6. The new page has var firstAmount = 0; in it

您应该:

使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆