This article mainly shares the sample code for js to implement the simple calculator function. It has a certain reference value. Let's take a look at the sample code below:
Simple Calculator
7 |
8 |
9 |
* |
4 |
5 |
6 |
/ |
1 |
2 |
3 |
+ |
DEL |
0 |
= |
- |
Script var numString = document. getElementsByClassName ("string") [0]; var buttonGroup = document. getElementsByTagName ("a"); var screen = document. getElementsByClassName ("string") [0]; var num1 = 0; var num2 = 0; var count = 0; var f; var flag = true; /* control the input number */var flag2 = true;/* control whether to continuously click the symbol */screen. onclick = function () {numString. innerHTML = "" ;}; for (var I = 0; I <buttonGroup. length; I ++) {ButtonGroup [I]. onclick = function () {switch (this. innerHTML) {case "0": case "1": case "2": case "3": case "4": case "5": case "6 ": case "7": case "8": case "9": if (! Flag) {numString. innerHTML = ""; flag2 = true;} flag = true; numString. innerHTML + = this. innerHTML; break; case "DEL": numString. innerHTML = numString. innerHTML. substr (0, numString. innerHTML. length-1); break; case "+": case "-": case "*": case "/": f = this. innerHTML; count ++; if (flag2) {flag = false;/* indicates the input symbol */if (count = 1) {num1 = numString. innerHTML;} else {flag2 = false; num2 = nu MString. innerHTML; numString. innerHTML = eval (num1 + f + num2); num1 = numString. innerHTML ;}} break; case "=": num2 = numString. innerHTML; numString. innerHTML = eval (num1 + f + num2); count = 0; flag =! Flag; break ;}} script
The above is all the content of this article. I hope this article will help you in your study or work, and I also hope to support PHP!
For more articles about how to implement simple calculator functions in js, please follow the PHP Chinese network!