我正在制定资金管理计划。有一个输入框,您必须输入您的收入。每当我输入我的号码并点击输入时,数字会显示在一边,但是当我添加另一个号码时,它不能正确累加。
HTML
<!DOCTYPE html>
<html>
<head>
<!-- Edit title -->
<title>Banking App</title>
<!-- Stylesheet -->
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
</head>
<body>
<div class="main">
<header>
<h1>Bank Account Manager</h1>
</header>
<div class="displayInfo">
<div class="displayBalance">
<h2 class="displayBalanceTag">Balance: <span class="displayBalanceNumber"></span></h2>
</div>
</div>
<div class="inputInfo">
<center>
<input type="text" name="earned" placeholder="How Much Have You Earned?" class="earned">
<input type="text" name="spent" placeholder="How Much Have You Spent?" class="spent">
</center>
</div>
</div>
<!-- JQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!-- Main.js -->
<script type="text/javascript" src="assets/js/main.js"></script>
</body>
</html>
JS
// VARIABLES
var balance; //stores users balance
var earnings; //stores users earnings
var earned = $(".earned"); //input users earnings
var spent = $(".spent"); //input users spendings
var displayBalanceNumber = $(".displayBalanceNumber"); //displays users balance
// START
$("document").ready(function () {
balance = 0;
init();
})
// INIT
function init() {
reset(); //resets everything
$(earned).bind("keypress", addEarnings);
}
function addEarnings(e) {
//check for keycode 13 ( enter key )
if(e.which === 13) {
earnings = $(this).val(); //get value from input
balance = balance + earnings;
displayBalanceNumber.html(balance);
displayBalanceNumber.html(balance);
}
}
// RESET
function reset() {
displayBalanceNumber.html(balance); //make value inside balance holder to 0
}
答案 0 :(得分:1)
您的行balance = balance + earnings;
会将earnings
视为字符串。将字符串添加到数字时,它会将所有字符串转换为字符串。您需要做的是将earnings
转换为整数。将该行替换为balance = balance + +earnings;
。 +
将earnings
转换为数字。