时间:2021-07-01 10:21:17 帮助过:3人阅读
本文实例为大家分享了JS实现简易计算器的具体代码,供大家参考,具体内容如下
<!DOCTYPE html> <html> <head> <title>14th_test</title> <meta charset="gb2312"> </head> <body> <h1>这是一个标题</h1> <p>以下是一个简易计算器</p> <table border="1" style="position:center;"> <tr> <th>第一个数</th> <td><input id="fir" type="text" /></td> </tr> <tr> <th>第二个数</th> <td><input id="sec" type="text" /></td> </tr> <tr> <td colspan="2"> <button type="button" οnclick="add()">+</button> <button type="button" οnclick="substract()">-</button> <button type="button" οnclick="multiply()">*</button> <button type="button" οnclick="divide()">/</button> </td> </tr> <tr> <td colspan="2"><p id="result"></p></td> </tr> </table> <script> var res; //保存计算结果 function add() { var first = document.getElementById("fir").value; var second = document.getElementById("sec").value; res = Number(first) + Number(second); //这里"+"两端必须Number类型转换,否则当成字符串连接 sent(res); } function substract() { var first = document.getElementById("fir").value; var second = document.getElementById("sec").value; res = first - second; sent(res); } function multiply() { var first = document.getElementById("fir").value; var second = document.getElementById("sec").value; res = first * second; sent(res); } function divide() { var first = document.getElementById("fir").value; var second = document.getElementById("sec").value; res = first / second; sent(res); } function sent(re) { document.getElementById("result").innerHTML = re; } </script> </body> </html>
output:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。