js实现一个简易计算器
人气:0<!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:
更多计算器功能实现,请点击专题: 计算器功能汇总 进行学习
您可能感兴趣的文章:
加载全部内容