我想制作一个计算器,但是我不知道如何正确获取算术符号。例如,加号“+”不是数字,所以我得到了NaN结果,但我现在真的无法想象如何通过正确的方式获取它或制作它... 我正在寻找一种只使用JavaScript且简单易懂的方法。
var num = document.getElementsByTagName("button");
for( var i = 0; i < num.length; i++ ){
num[i].addEventListener("click", getNum);
var x = Number(num[i].value);
var y = Number(num[i].value);
}
var result = document.getElementById("result");
var numsRes = document.getElementById("numsRes");
numsRes.addEventListener("click", getResult)
var plus = document.getElementById("plus");
function getResult(){
// if( )
result.value = parseInt(x) + parseInt(y);
}
function getNum(){
result.value += this.value;
// if( this.value == "+" ){
// result.value += this.value;
// }
}
button{
width: 30px;
height: 30px;
margin: 5px 0;
}
#result{
width: 130px;
height: 30px;
display: block;
}
<div id="calculator">
<input id="result">
<button type="button" value="0">0</button>
<button type="button" value="1">1</button>
<button type="button" value="2">2</button>
<button type="button" value="3">3</button>
<br>
<button type="button" value="4">4</button>
<button type="button" value="5">5</button>
<button type="button" value="6">6</button>
<button type="button" value="7">7</button>
<br>
<button type="button" value="8">8</button>
<button type="button" value="9">9</button>
<button type="button" value="-">-</button>
<button type="button" id="plus" value="+">+</button>
<br>
<button type="button" value="*">*</button>
<button type="button" value="/">/</button>
<button type="button" id="numsRes" value="=">=</button>
<button type="button" value="C">C</button>
</div>