Home > Article > Web Front-end > The simplest way to implement calculator function in JS
This time I will bring you the simplest way to implement the calculator function with JS. What are the precautions for implementing the calculator function with JS. The following is a practical case, let’s take a look.
Specific code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>www.jb51.net JS计算器</title> <script type="text/javascript"> // window.onload 获取元素getElementById window.onload = function(){ var oTxt1 = document.getElementById('val01'); var oTxt2 = document.getElementById('val02'); var oFuhao = document.getElementById('fuhao'); // 这三个要放在button函数里面,因为s1.value是获取input里面的输入,但是这个时候还没有输入了 // var iNum1 = oTxt1.value; // var iNum2 = oTxt2.value; // var iNum3 = oFuhao.value; oBtn = document.getElementById('btn'); // 计算按钮点击事件 oBtn.onclick = function(){ var iNum1 = oTxt1.value; var iNum2 = oTxt2.value; var iNum3 = oFuhao.value; var iResult; //如果两个输入有一个是空的话 //return是让if里面执行结束 if (iNum1=='' || iNum2=='') { alert('不能为空'); return; } //isNaN() 如果是true,说明是非数字,所以如果两个输入中有非数字,就提示alert if (isNaN(iNum1) || isNaN(iNum2)) { alert('不能有字母'); return; } //对+-*/四个操作对应的value进行判断 //如果直接iNum1+iNum2 输出的结果是字符串的拼接 12+24 1224 所以要转换成parseInt整数 if (iNum3 == 0) { iResult = parseInt(iNum1) + parseInt(iNum2) } else if (iNum3 == 1) { iResult = parseInt(iNum1) - parseInt(iNum2) } else if (iNum3 == 2) { iResult = parseInt(iNum1) * parseInt(iNum2) } else if (iNum3 == 3) { iResult = parseInt(iNum1)/parseInt(iNum2) } alert(iResult); } } </script> </head> <body> <h3>计算器</h3> <input type="text" id="val01"> <select id="fuhao"> <option value="0">+</option> <option value="1">-</option> <option value="2">*</option> <option value="3">/</option> </select> <input type="text" id="val02"> <input type="button" id="btn" value="计算"> </body> </html>
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
How to choose vue’s components and framework structure
The above is the detailed content of The simplest way to implement calculator function in JS. For more information, please follow other related articles on the PHP Chinese website!