I recently wrote a simple calculator using javascript. I tested it myself and it seemed fine. Let me show you the interface first:
The interface is like this, but what is the function? Woolen cloth?
Now it is just a simple standard calculator that can perform continuous operations of addition, subtraction, multiplication and division, as well as remainder operations. If an error occurs when the dividend is divided by zero, a prompt will be given below, just like this:
I don’t know how to write it, but for novices, this is definitely A big meal, with a lot of things you can come into contact with and learn from. If there are any experts who see any omissions or mistakes in it, I hope they will give you some advice and pointers.
Paste the code below, I hope there are enough comments inside.
js part:
var num=0,result=0,numshow="0"; var operate=0; //判断输入状态的标志 var calcul=0; //判断计算状态的标志 var quit=0; //防止重复按键的标志 function command(num){ var str=String(document.calculator.numScreen.value); //获得当前显示数据 str=(str!="0") ? ((operate==0) ? str : "") : ""; //如果当前值不是"0",且状态为0,则返回当前值,否则返回空值; str=str + String(num); //给当前值追加字符 document.calculator.numScreen.value=str; //刷新显示 operate=0; //重置输入状态 quit=0; //重置防止重复按键的标志 } function dzero(){ var str=String(document.calculator.numScreen.value); str=(str!="0") ? ((operate==0) ? str + "00" : "0") : "0"; //如果当前值不是"0",且状态为0,则返回当str+"00",否则返回"0"; document.calculator.numScreen.value=str; operate=0; } function dot(){ var str=String(document.calculator.numScreen.value); str=(str!="0") ? ((operate==0) ? str : "0") : "0"; //如果当前值不是"0",且状态为0,则返回当前值,否则返回"0"; for(i=0; i<=str.length;i++){ //判断是否已经有一个点号 if(str.substr(i,1)==".") return false; //如果有则不再插入 } str=str + "."; document.calculator.numScreen.value=str; operate=0; } function del(){ //退格 var str=String(document.calculator.numScreen.value); str=(str!="0") ? str : ""; str=str.substr(0,str.length-1); str=(str!="") ? str : "0"; document.calculator.numScreen.value=str; } function clearscreen(){ //清除数据 num=0; result=0; numshow="0"; document.calculator.numScreen.value="0"; } function plus(){ //加法 calculate(); //调用计算函数 operate=1; //更改输入状态 calcul=1; //更改计算状态为加 } function minus(){ //减法 calculate(); operate=1; calcul=2; } function times(){ //乘法 calculate(); operate=1; calcul=3; } function divide(){ //除法 calculate(); operate=1; calcul=4; } function persent(){ //求余 calculate(); operate=1; calcul=5; } function equal(){ calculate(); //等于 operate=1; num=0; result=0; numshow="0"; } // function calculate(){ numshow=Number(document.calculator.numScreen.value); if(num!=0 && quit!=1){ //判断前一个运算数是否为零以及防重复按键的状态 switch(calcul){ //判断要输入状态 case 1:result=num+numshow;break; //计算"+" case 2:result=num-numshow;break; //计算"-" case 3:result=num*numshow;break; case 4:if(numshow!=0){result=num/numshow;}else{document.getElementById("note").innerHTML="被除数不能为零!"; setTimeout(clearnote,4000)} break; case 5:result=num%numshow;break; } quit=1; //避免重复按键 } else{ result=numshow; } numshow=String(result); document.calculator.numScreen.value=numshow; num=result; //存储当前值 } function clearnote(){ //清空提示 document.getElementById("note").innerHTML=""; }
html part:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>写给新手:js表单操作(四) 简单计算器(二)</title> <style type="text/css"> body { font-size:12px; font-family:Arial, Georgia, "Times New Roman", Times, serif; color:#555; text-align:center; background-color:#e2e2e2; } h6{ margin:0; font-size:12px; } #calculator { width:240px; height:auto; overflow:hidden; margin:10px auto; border:#fff 1px solid; padding-bottom:10px; background-color:#f2f2f2; } #calculator div { clear:both; } #calculator ul{ padding:0; margin:5px 14px; border:#fff 1px solid; height:auto; overflow:hidden } #calculator li{ list-style:none; float:left; width:32px; height:32px; margin:5px; display:inline; line-height:32px; font-size:14px; background-color:#eaeaea; } #calculator li.tool{ background-color:#e2e2e2; } #calculator li:hover{ background-color:#f9f9f9; cursor:pointer; } #calculator li:active{ background-color:#fc0; cursor:pointer; } #calculator li.tool:active{ background-color:#d8e8ff; cursor:pointer; } #calcu-head { text-align:left; padding:10px 15px 5px; } span.imyeah { float:right; color:#ccc; } span.imyeah a{ color:#ccc; } .screen{ width:200px; height:24px; line-height:24px; padding:4px; border:#e6e6e6 1px solid; border-bottom:#f2f2f2 1px solid; border-right:#f2f2f2 1px solid; margin:10px auto; direction:ltr; text-align:right; font-size:16px; color:#999; } #calcu-foot{ text-align:left; padding:10px 15px 5px; height:auto; overflow:hidden; } span#note{ float:left; width:210px; height:auto; overflow:hidden; color:red; } span.welcome{ clear:both; color:#999; } span.welcome a{ float:right; color:#999; } </style> <script language="javascript"> //此处插入上面的js代码 </script> </head> <body> <div id="calculator"> <div id="calcu-head"><span class="imyeah">© <a href="http://www.cnblogs.com/imyeah/" target="_blank">I'm Yeah!</a></span><h6 id="简单的计算器">简单的计算器</h6></div> <form name="calculator" action="" method="get"> <div id="calcu-screen"> <!--配置显示窗口,使用onfocus="this.blur();"避免键盘输入--> <input type="text" name="numScreen" class="screen" value="0" onfocus="this.blur();" /> </div> <div id="calcu-btn"> <ul> <!--配置按钮--> <li onclick="command(7)">7</li> <li onclick="command(8)">8</li> <li onclick="command(9)">9</li> <li class="tool" onclick="del()">←</li> <li class="tool" onclick="clearscreen()">C</li> <li onclick="command(4)">4</li> <li onclick="command(5)">5</li> <li onclick="command(6)">6</li> <li class="tool" onclick="times()">×</li> <li class="tool" onclick="divide()">÷</li> <li onclick="command(1)">1</li> <li onclick="command(2)">2</li> <li onclick="command(3)">3</li> <li class="tool" onclick="plus()">+</li> <li class="tool" onclick="minus()">-</li> <li onclick="command(0)">0</li> <li onclick="dzero()">00</li> <li onclick="dot()">.</li> <li class="tool" onclick="persent()">%</li> <li class="tool" onclick="equal()">=</li> </ul> </div> <div id="calcu-foot"> <span id="note"></span> <span class="welcome">欢迎使用javascript计算器!<a href="http://www.cnblogs.com/imyeah" target="_blank">反馈</a></span> </div> </form> </div> </body> </html>
For more articles related to simple calculators written in javascript, please pay attention to the PHP Chinese website!

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor