![](/img/trans.png)
[英]How do I make it so each button I press in my calculator app combines the numbers together?
[英]TOP Calculator: How do I make a function to operate on the numbers in a string?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title> Calculator </title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<header>
<h1>Bria's Calculator</h1>
</header>
<div id="container">
<form name="calculate">
<input id="input" type="text" name="output" placeholder="0"><br/>
<input id="button1" type="button" value="1"/>
<input id="button2" type="button" value="2"/>
<input id="button3" type="button" value="3"/>
<input id="button/" type="button" value="/"/> <br/>
<input id="button4" type="button" value="4"/>
<input id="button5" type="button" value="5"/>
<input id="button6" type="button" value="6"/>
<input id="button*" type="button" value="*"/><br/>
<input id="button7" type="button" value="7"/>
<input id="button8" type="button" value="8"/>
<input id="button9" type="button" value="9"/>
<input id="button-" type="button" value="-"/><br/>
<input id="button(" type="button" value="("/>
<input id="button)" type="button" value=")"/>
<input id="button0" type="button" value="0"/>
<input id="button+" type="button" value="+"/><br/>
<input id="buttonc" type="button" value="c" style="background:red;"/>
<input id="button." type="button" value="."/>
<input id="button=" type="button" value="="/>
<input id="button%" type="button" value="%"/><br/>
</form>
</div>
<script type="text/javascript" src="calculator.js"></script>
</body>
</html>
const input=document.getElementById("input");
const container=document.getElementById("container");
const calc =document.getElementById("button=");
container.addEventListener("click", function(e){
buttonClick(e.target.id);
});
//use event parameter of target to identify what's inside the id which are the buttons
calc.addEventListener("click", operate);
function buttonClick(buttonId){
if ((buttonId !="buttonc") && (buttonId !="button=")){
let button=document.getElementById(buttonId);
let tmp=buttonId;
tmp=tmp.replace("button", "");
entries(tmp);
}
};
//use 'replace' so when buttons are clicked it removes preface(button) and the id is just a number in the string format
function entries(tmp){
input.value += tmp;
}
//concatenating values entered by pressing buttons within container
function operate (){
if(input.value=="."){
alert("Please enter a math equation");
}
}
到目前為止,我已經能夠將數字連接成一個字符串,但現在我需要對它們進行實際操作。 TOP 不鼓勵使用 eval,所以我只想知道如何設置 function 來加、除、乘和減我在沒有 eval() 的輸入形式中調用的數字。 我已經為上下文提供了我的 HTML 代碼。
您有幾個選項可以根據您期望的輸入將連接的字符串轉換為數字。 我會推薦以下兩個之一:
parseFloat()
- 將帶小數點的字符串轉換為浮點數。
parseInt(x,10)
- 將字符串的 integer 值轉換為 integer (不會處理任何小數點)。 注意第二個參數 (10)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.