$(onReady);
function onReady() {
console.log('log inside of onReady');
$(".calculatorNum").on('click', buttonClicked);
}//end of onReady
function buttonClicked() {
console.log('buttonClicked');
var input = $("#inputField").val($(this).text());
input += input;
}
button {
height:30px;
width:30px
}
#clearButton{
width:64px
}
#inputField{
margin-bottom: .5em;
height:2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Calculator</title>
<link rel="stylesheet" href="styles/style.css">
<script
src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script src="scripts/scripts.js" charset="utf-8"></script>
</head>
<body>
<h1>Calculator</h1>
<div class="numContainer">
<input id = 'inputField' type="text" placeholder="input">
<br>
<button class ='calculatorNum' type="button" name="button">1</button>
<button class ='calculatorNum' type="button" name="button">2</button>
<button class ='calculatorNum' type="button" name="button">3</button>
<button id = 'addButton' class ='calculatorNum' type="button" name="button">+</button>
<br>
<button class ='calculatorNum' type="button" name="button">4</button>
<button class ='calculatorNum' type="button" name="button">5</button>
<button class ='calculatorNum' type="button" name="button">6</button>
<button id = 'subButton' class ='calculatorNum' type="button" name="button">-</button>
<br>
<button class ='calculatorNum' type="button" name="button">7</button>
<button class ='calculatorNum' type="button" name="button">8</button>
<button class ='calculatorNum' type="button" name="button">9</button>
<button id = 'multButton' class ='calculatorNum' type="button" name="button">X</button>
<br>
<button id = 'clearButton' class ='calculatorNum' type="button" name="button">Clear</button>
<button class ='calculatorNum' type="button" name="button">/</button>
<button class ='calculatorNum' type="button" name="button">=</button>
</div>
<!-- <button id = 'addButton' class ='calculatorButton' type="button" name="button">+</button>
<button id = 'subButton' class ='calculatorButton' type="button" name="button">-</button>
<button id = 'multButton' class ='calculatorButton' type="button" name="button">X</button>
<button id = 'divButton' class ='calculatorButton' type="button" name="button">/</button> -->
</body>
</html>
我希望每次单击按钮时,它都会在输入字段中根据我单击的按钮的文本不断添加值。
最佳答案
您可能需要一个全局变量:
var input="";
function buttonClicked() {
console.log('buttonClicked');
$("#inputField").val((input+=$(this).text()));
}
一些解释:
您在buttonClicked内部声明了输入变量。因此,该函数运行后会被垃圾回收,因此每次单击后输入都会丢失。如果要防止这种情况,请在全局范围内使输入全局槽声明它。然后,您可以将按钮值(+ =)附加到输入中,并显示该值。如果希望输入为数字,则可以执行以下操作:
var input=0;
function buttonClicked() {
console.log('buttonClicked');
$("#inputField").val((input+=+$(this).text()));
}