Js implements simple calculator Functions

Source: Internet
Author: User
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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.